sql查詢
1.Where約束條件
1. select * from table where id >=1 and id <=9;
2. select * from table where id between 3 and 9;
3. select * from table where id in [1,2,3];
4. select * from table where id not in (1,2,3)
5. select * from table where id
6 . select * from table where post not Null;
通配符:
7. select * from table where name like ‘%s’
8. select * from table where name like '____' #查詢名字為4個的
select * from table where char_length(name) = 4;
2.group_by
分組使用的聚合函數: max,min,avg,count,sum
1. select avg(id) from table; 默認為一組
2. select count(salary) from table group_by 部門;
分組的時候只能拿到,分組的依據,以及聚合函數的使用
就是要拿到其他字段怎么辦
分組后使用的group_concat(name,":",salary) 中間可以拼接;
分組前使用的 concat('name:',name) as 別名
插曲:as的用法,起別名,可以給字段,也可以給表
select name as myname form table
其中as可以省略
select name myname from table #這種語意不明確,不建議使用
3.having
select sum(salary) from table where id >10 group_by 部門 having sum(salary) >10;
4.where group_by having 的前后順序
where >group_by> having
注意:
聚合函數不能跟在where之后
5.distinct去重
select distct * fom table;不能去重,有id,很容易忽視的點
select distict name from table; #可以去重
6.limit 分頁
selesct * from table limit 5; #拿五個
selesct * from table 0,5;#從第0個開始,往后取5條;
5,5; #
7.正則
select * from table where name=regexp '^l.*(n|y)$';
8.連表
select * from table,table2; #笛卡爾積;
select * from table inner join table2;
select * from table left join table2;
select * from table right join table2;
select * from table; union select *from table2;
9.復制表
create table new_table select name from old_table; #查詢結果為一張虛擬表,可以保存起來,僅僅是有數據,沒有外鍵;
10.數據展示
select * from table\G; #當數據多的時候,用這個展示一行行
11.跨表查詢的兩種方式;
1.連表:
把表連起來,然后再查;
2.子查詢:
先查詢一張表,把這張表當作其他查詢的依據;
補充
1.case when min(num) < 10 Then 0 ELSE min(num)
2.if(isnull(name),'無名氏',name)