數據結構:
1.彙總函數:
avg(), count(), max(), min(), sum()
select avg(price), count(price), max(price), min(price), sum(price) from shopping;
2.數據分組:
mysql提供了數據分組的方法,group by對列數據進行分組統計
select price,count(price) from shopping group by price;
3.過濾分組,行的過濾可以使用where,having,分組的過濾只能使用having,不能用where
select price,count(price) from shopping group by price having price='66';
注意:
1.關鍵字使用順序
select xxx from xxx group by xxx order by xxx limit xxx;
select xxx from xxx where xxx order by xxx limit xxx;
2.group by的功能是進行分組,order by 是排序,各司其職,group by的排序不靠譜
4.聯結表(聯結表是對兩個及以上的表進行篩選)
select shopping.name,custom.name,custom.id from shopping,custom where shopping.id = custom.id order by custom.id;
可以使用表別名降低select語句的長度 select a.name,b.name b.id from shopping as a ,custom as b where a.id=b.id order by b.id;
如果沒有where的篩選規則,則根據笛卡兒積的規則返回兩個表的m*n數據組合
select shopping.name,custom.name,custom.id from shopping,custom;
mysql還可以通過inner join ... on的方式進行聯結表的查詢
select shopping.name as shopping_name, custom.name as custom_name, custom.id as custom_id from shopping inner join custom on shopping.id=custom.id order by custom.id;
還可以使用別名,降低select語句的長度select a.name,b.name,b.id from shopping as a inner join custom as b on a.id=b.id order by b.id;
注意:
表別名和列別名不一樣,表別名不會作爲真實數據返回,列別名會做爲真實的字段返回
5.組合查詢
在需要獲取兩個表中同樣的數據時,可以使用組合查詢的方式,關鍵字爲union
select name,id from shopping union select name,id from custom;
同樣也可以在一個表裏面使用組合查詢,在篩選條件不同時可以使用
select name,id from shopping where id<='2' union select name,id from shopping where id='5';
注意:使用組合查詢時,返回的結果必須是一樣的,必須對同一個表或者不同的表返回查詢結果的字段必須相同