insert into Persons values (1,'Adams','John','Oxford Street','London');
insert into Persons (LastName,FirstName)values ('Bush','George');
update Persons set Address = 'Fifth Avenue',City = 'New York' where LastName = 'Bush';
delete from Persons where id =2;
· 比较运算符:
1. <
2. <=
3. !=或 <>
4. >=
5. =
6. >
7. in
8. between 值1 and 值 2
· 逻辑运算符:
1. not !
2. or ||
3. and &&
· 模糊查询:like
select * from Persons where FirstName like 'J%';
#通配单个字符
select * from Persons where FirstName like 'Joh_';
· 算术函数
select max(age) from Persons;
select min(age) from Persons;
select sum(age) from Persons;
select avg(age) from Persons;
select count(*) from Persons;
· 分组查询:group by
select count(*),City from Persons group by City;
· 取别名: as
select count(*),City as c from Persons group by c; #可省略 as select count(*),City c from Persons group by c;
· 对结果集再次查询: having
select count(*),City as c from Persons group by c having c is not null;
· 排序: order by
可以根据字段排序,可以升序或降序,默认升序排列
字段名 desc 按降序排序
asc 按升序排序
select * from Persons order by age desc;
# 先按字段1 ,字段1相同 按 字段2
select * from Persons order by age desc, FirstName;
# limit [offset][N] offset : 偏移量
# 在语句最后,起到限制条目的作用
select * from Persons order by age desc limit 2;
select * from Persons order by age desc limit 1,2;
select * from Persons where age in (select max(age) from Persons);
select * from (select * from Persons where City is not null) as temp where Id > 1;
1.union
作用:把2次或多次查询结果联合起来
select Id , FirstName from Persons union select Id , CarName from Car;
要求:两次查询的列数一致
建议:查询每一列,相应的列类型也一样
注意:
· 可以来自多张表;
· 多次sql语句取出的列名可以不一致,以第一次为准
· 如果不同语句,取出的行结果完全一致,相同的行会被合并,可以使用 union all ,不合并相同结果
· 如果子句中有 order by,limit 需加小括号包起来,推荐放在所有子句后,即对合并结果来排序
· 在子句中,order by 配合 limit 使用才有意义,不配合使用会被语法分析去除
select Id , FirstName from Persons order by age limit 2) union select Id , CarName from Car;
2.左连接
左连接以左表为准,去右表匹配数据,匹配不到用 null 补充
select p.Id , FirstName , CarName from Persons p left join Car c on p.Id = c.PersonId;
3.右连接
右连接以右表为准,去左表匹配数据,匹配不到用 null 补充
select p.Id , FirstName , CarName from Persons p right join Car c on p.Id = c.PersonId;
4.内连接
查询左右表都有的数据,不要左右中 null 部分,即左右表的交集
select p.Id , FirstName , CarName from Persons p inner join Car c on p.Id = c.PersonId;
5.外连接
mysql 不支持 全外连接