在上篇博客MySql必知必會實戰練習(一)表建立和數據添加中完成了各表的建立和數據添加,下面進行數據檢索和過濾操做。html
select--->DISTINCT--->from--->where--->GROUP BY--->HAVING--->ORDER BY--->LIMITpost
select verd_id from products;ui
使用DISTINCT檢索出不一樣值的列表
select DISTINCT verd_id from products;spa
首先看下下面3個查詢語句的結果:htm
select count(*) from products;
select * from products where verd_id = 1003;
select count(*) from products where verd_id = 1003;blog
(1)(2)
(3)
排序
(1)表示products表的總項數14ip
(2)列出了verd_id爲1003的全部項get
(3)顯示verd_id爲1003的總項數7博客
再看下面語句的輸出結果:
select verd_id, count(*) as num_prods from products GROUP BY verd_id;
結果一目瞭然,分別對verd_id進行分組,並顯示各組的總項數。
注:若是再select中使用表達式,則必須再GROUP BY字句中指定相同的表達式,不能使用別名。
HAVING語句主要是對分組語句進行過濾,WHERE過濾指定的是行而不是分組,事實上,WHERE沒有分組的概念
HAVING與WHERE的惟一差異就是WHERE過濾行,HAVING過濾分組
select verd_id, count(*) as num_prods from products GROUP BY verd_id HAVING count(*)>2;
select verd_id, count(*) as num_prods from products GROUP BY verd_id HAVING verd_id = 1003;
select cust_name,cust_address,cust_zip from customers;
對cust_zip排序
select cust_name,cust_address,cust_zip from customers ORDER BY cust_zip;
對多列進行排序
select cust_name,cust_address,cust_zip from customers ORDER BY cust_address,cust_zip;
指定排序方向:默認升序(ASC),爲了進行降序排序,必須指定DESC關鍵字
select cust_name,cust_address,cust_zip from customers ORDER BY cust_zip DESC;
LIMIT關鍵子對輸出的行數限制,指定其實行和行數
select cust_name,cust_address,cust_zip from customers ORDER BY cust_zip DESC LIMIT 2,4;
select verd_id, count(*) as num_prods from products GROUP BY verd_id HAVING count(*) > 0 ORDER BY verd_id DESC LIMIT 1,3;