SQL常用語法
Order by 應位於where子句後;Having類似於where,不同的是where過濾的物件是行,而having過濾的物件是分組,所以having 在group by後使用
Select region,name from world.country; |
返回Region列和name列 |
Select * from world.country; |
返回所有列 |
select distinct region from world.country; |
返回不同的值 |
select region from world.country limit 5 offset 10; |
限制返回第10行起的後面5行資料 (第一個被檢索的是第0行) |
select region from world.country order by region; |
排序(升序) |
select region,name from world.country order by region,name; |
首先按region排序,在相同的region中再按name進行排序(升序) |
select region from world.country order by region desc; |
排序(降序) |
select region from world.country where region="western europe"; |
過濾 |
select * from world.country where indepyear between 1918 and 1962; |
1918<=Indepyear<=1962 |
where indepyear is null |
不包含值的 |
select * from world.country where indepyear between 1918 and 1962 and population>14786000; |
兩個過濾條件 |
select region from world.country where region="western europe" or region="south america"; |
滿足其中一個過濾條件 (and優先順序比or更高,組合使用需要加括號) |
select region from world.country where region in("western europe","south america"); |
X = In(a,b,c,…)等價於X=a or X=b or X=c… |
where region not in("western europe","south america"); |
相當於取反 |
where region like 'Ca%'; |
Like是萬用字元,%表示出現任意次數 找出所有由Ca開頭的region,不需要準確給出匹配的值 %Ca%匹配任意位置上包含Ca的值,不論前後出現了什麼字元 |
select concat(region,' | ',name) from world.country |
Concat(a,b,c,…)拼接a,b,c |
select concat(region,' | ',name) as new_column from world.country |
拼接後按照new_column(別名)這一列來返回,任何客戶端都可以使用這一列 |
select Avg(Population*IndepYear) as avg_column from world.country |
求出Population*IndepYear的平均值,別名為avg_column |
select count(Population) as count_column from world.country |
對有population值的行計數 |
select max(Population) as max_column from world.country |
返回population的最大值 |
select sum(Population>=0) as sum_column from world.country; |
返回Population>=0的行數之和 |
select sum(Population) as sum_column from world.country; |
返回所有的population之和 |
select sum(distinct Population) as sum_column from world.country; |
返回所有不同的poulation的和(預設為all) |
select region, count(*) as count_column from world.country group by region; |
按照region分組,然後計算每個組內包含的行數 |
select region,count(*) as count_column from world.country group by region having count_column>5; |
Having類似於where,不同的是where過濾的物件是行,而having過濾的物件是分組,只顯示count_column大於5的分組 |
alter table world.country add sex int; |
增加一列,列名為add,資料的型別為int |
alter table world.country drop sex; |
刪除sex這一列 |
alter table world.country modify population int ; |
更改population列的屬性 |
alter table world.country change column population abc int; |
修改population列名為abc,int為屬性 |
update world.country set population=0 where code="aia"; |
更新where找出的行的population值為0 |