大家好,我是anyux。上一節本節是對於SQL語句select詳細演示操作,本節是對於select練習演示操作。
select查詢操作
統計中國每個省的總人口數,列印總人口數小於100萬的
use world;select district,sum(population)from citywhere countrycode='CHN'group by districthaving sum(population) > 1000000;
查看中國所有的城市,並按人口數排序(從大到小)
select namefrom citywhere countrycode='CHN'order by population desc;
統計中國每個省的總人口數量,按照總人口從大到小排序
select district,sum(population)from citywhere countrycode='CHN'group by districtorder by sum(population) desc;
統計中國,每個省的總人口,找出總人口大於500萬的,並按總人口從大到小排序,只顯示前三名
select district,sum(population)from citywhere countrycode='CHN'group by districthaving sum(population) > 5000000order by sum(population) DESC limit 3;
union和union all
union 和union all 的區別
union會做去除重複處理,性能比union會差一些
union all 不做去除重複處理
作用:多個結果集合併查詢的功能
查詢中國或美國的城市信息
select * from city where countrycode in ("CHN",'USA');
改寫後的SQL語句,索引等級會提高
select *from citywhere countrycode='CHN'union allselect *from citywhere countrycode="USA";
統計中國,每個省的總人口,找出總人口大於500萬的,並按總人口從大到小排序,顯示前三名和後三名
注意,如果這裡使用了子查詢,因為兩個查詢結果都使用了order by 子句,為排除報錯使用子查詢
select *from (select district,sum(population)from citywhere countrycode='CHN'group by districthaving sum(population) > 5000000order by sum(population) desc limit 3 ) munion allselect * from (select district,sum(population)from citywhere countrycode="CHN"group by districthaving sum(population) > 5000000order by sum(population) asclimit 3)n;
多表連接查詢(內連接)
基本語法
最核心的是找到多張表之間的關聯條件列,比如下面示例中city表的countrycode和country表中的code相關聯列書寫時,格式必須為 表名.列,因為如果不標識出來,就無法確定是哪個表的列進行關聯表的關聯列使用=(等號)連接如city.countrycode=country.code要查詢的數據也必須將列前面加上表名稱關聯條件時使用on連接條件,如(from city join country on city.countrycode=country.code)將所有的過濾、分組、排序等條件按順序寫在on的後面多張表關聯A JOIN B on A.x=B.y JOIN B C on B.m=C.n建議使用數據少的表做為連接的驅動表,將數據行最少的放在最左邊,後續所有表的關聯列儘量是主鍵或唯一鍵,至少建立一個索引
查詢世界上小於100人的城市,所在的國家名,國土面積,城市名,人口數
select country.name ,country.surfaceArea,city.name ,city.populationfrom cityjoin countryon city.countrycode=country.codewhere city.population < 100;
使用別名做簡化處理
select B.name ,B.surfaceArea,A.name ,A.populationfrom city as Ajoin country as Bon A.countrycode=B.codewhere A.population < 100;
查詢城市shenyang,城市人口,所在國家名(name)及國土面積(SurfaceArea)
select A.name,A.population,B.name,B.surfacearea from city as A join country as B on A.countrycode = B.code where A.name='shenyang';
別名
Mysql別名分為列別名,和表別名
表別名可以出現在任意子句中。列別名可以使用ORDER BY,GROUP BY和HAVING子句中的列別名來引用該列
注意:不能在WHERE子句中使用列別名。原因是當MySQL評估求值WHERE子句時,SELECT子句中指定的列的值可能尚未確定。
select A.name as 城市名稱,A.population as 城市人口,B.name as 國家名稱,B.surfacearea as 國家人口from city as Ajoin country as Bon A.countrycode = B.codewhere A.name='shenyang';
本節是對於SQL語句select練習演示。其中如有不足還各位同學指出。下一節將進行更詳細的複雜的select練習操作。