sql查詢語句


select *from table where ......  #先執行的是from   后執行的是 where

查詢有很多種,select 、where  、group by、 having、oder by、limit 、regexp、like、

1.where

  #篩選id大於3 小於6 

  select * from table where id > =3 and id < =6;

  #篩選出 id 等於 1 或者  等於2 或者等於3 

  select * from table where id = 1 or id = 2 or id = 3;

  #篩選出 id 等於 1 或者  等於2 或者等於3 

  select *from table where id in (1,2,3);

  #篩選出id在3到6之間的

  select *from table where id betweem 3 and 6;

  #篩選 id不在 元組中的數的

  select *from table where id not in (1,3);

  #篩選 含有名字含有a的

  select *from table  where name like '%a%';

  #篩選名字中為4個字符的

  select *from table  where name like '____'; 

  select *from table  where char_length(name) = 4;

  #查詢為空的

  select * from table where name is null

#  補充:

  mysql  對大小寫不敏感的,%意味着 0或多個字符,而 _意味着1個字符

  char_length()  可以查詢數據的長度

2.group by  # 顧名思義,是用來 分組

  select  * from table group by post ;#按部門分

  在沒有開啟嚴格模式是可以執行的

  設置嚴格模式  set  global sql_mode = ‘strict_trans_tables,only_full_group_by'

  分組不能拿單獨的數據了

  select post from table group by post;

  #獲取部門的最高薪資,

  select post ,max(salary) from table group by post;

  select post as '部門' ,max(salary) as '薪資' from table group by post;

  最先 min  平均  avg  總和  sum

  #統計部門人數

  select port ,count(id)  from table group by port

  #獲取分組后,字段的值

  select post ,group_concat(name,':',salary) from table group by post;

  #注意: 可以拼接 group_concat(name,salary ,'_haha');

  !!!cancat  不分組的時候用的,默認起始為一組,

   as  可以給表臨時起名

  #select  t1.id ,t1.name from bjadjkabdjah as t1 ;   當表名字很長的時候

  #查詢年薪  12  薪

  select name ,salary* 12 from table ;  可以數字運算   

  !!!!!! 分組注意點: where group by 同時出現,group by 要在where 后面;

    聚合函數,只能在from前面;

  #統計 各部門 年齡在30以上,的員工平均薪資;

  select post ,avg(salary) from table where age >30 group by post;

3.having #分組之后的篩選條件

  #having 的語法和where 一樣,只不過是在分組后的過濾操作,即having 是可以直接用聚合函數的

  select port avg(salary) from table where age > 30 group by post having avg(salary) > 1000;

4.dictinct 去重

  #一定是完全一樣的數據,才能去重,不要忽視主鍵 id 的存在;

  select dintinct id,age from table;

  select dintinct age from table;

5. order by#排序

  select *from table  order by salary #默認是升序

  #升序  asc  降序   desc order by 可以添加多個;

  select *from table order by desc ,salary asc;

 

6.limit #限制展示的數據,分頁;

  select *from table limit 3;#只顯示3條;

  select *from table limit(n,m) #起始位置n,開始取m條數據;

7.正則

  select *from where name regexp '^j.*(n|y)$'   #以j開頭,n或者y結尾的

 

連表

  四種,inner join    left join ,right join , union

  inner 只顯示都存在的

  left  顯示 左邊

  right  顯示右邊

  union 顯示 兩邊

子查詢 就是我們解決問題的步驟,

  select *from emp where dep_id in (select id from dep where name = '技術' or name = '人力資源')

 

總結:

  表的查詢結果,可以作為其他表的查詢條件;

  也可以通過別名的方式把它作為一個虛擬表很其他表關聯

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM