/*
begin:单表检索
*/
\c study;
--按字段检索SELECT city ,temp_lo,temp_hi,prcp,dateFROM weather;--整合字段信息并重命名SELECT city, (temp_hi + temp_lo) / 2AS temp_avg,dateFROM weather;--按条件检索 AND OR NOT....SELECT * FROM weather WHERE city = 'San Francisco'AND prcp > 0.0;--要求返回结果是排序好的SELECT * FROM weather ORDERBY city;SELECT * FROM weather ORDERBY city,temp_lo;--要求消除重复结果SELECTDISTINCT city FROM weather;SELECTDISTINCT city FROM weather ORDERBY city;--自连接 利用表行间字段的关系检索SELECT W1.city,W1.temp_lo AS low, W1.temp_hi AS high, W2.city,W2.temp_lo AS low,W2.temp_hi AS high
FROM weather W1, weather W2 where W1.temp_lo < W2.temp_lo AND W1.temp_hi > W2.temp_hi;/*
next:表间连接检索 -- 内连接(消除其他表不存在行)
表间无概念上的主次关系
*/--选取表weather city字段和cities name相同的行SELECT * FROM weather ,cities WHERE city = name;--不需要重复信息SELECT city/*or name*/,temp_lo,temp_hi,prcp,date,location FROM weather,cities WHERE city = name;--如果表间有重复名称,用字段全称限定SELECT weather.city,weather.temp_lo,weather.hi,weather.prcp,weather.date,cities.location FROM weather, cities WHERE cities.name = weather.city;--使用inner join ....on代替上述语法SELECT * FROM weather INNERJOIN cities ON(weather.city = cities.name);/*
next:表间连接检索 --外连接(其他表不存在数据用“空值”代替产生新行)
*/--右表不存在的数据字段用空值代替SELECT * FROM weather LEFTOUTERJOIN cities ON (
weather.city = cities.name);--左表不存在的数据字段值用空值代替SELECT * FROM weather RIGHTOUTERJOIN cities ON (
weather.city = cities.name);--可以看作左外连接和右外连接的并集SELECT * FROM weather FULLOUTERJOIN cities ON (
weather.city = cities.name);
\c study;
/*
begin:聚集函数 综合表的行得到结果
*/SELECTmax(temp_lo) FROM weather;--注:聚集函数不能用于where子集SELECT city FROM weather where temp_lo = (selectmax(temp) FROM weather);--聚集函数用于GROUP BY 子句SELECT city,max(temp_lo) FROM weather GROUPBY city;--使用HAVING 过滤分组 注:HAVING子句只能出现聚集函数或者GROUP BY子句中的条件SELECT city,max(temp_lo) FROM weather GROUPBY city
HAVINGmax(temp_lo) < 40;--LIKE 子句 SELECT city, max(temp_lo) FROM weather WHERE city LIKE'S%'GROUPBY city HAVINGmax(temp_lo) > 40;/*
next:更新 UPDATE tablename SET column = somevalue....
*/UPDATE weather SET temp_hi = temp_hi - 2,temp_lo = temp_lo - 2WHEREdate > '1994-11-28';/*
next:删除 DELETE FROM tablename..无WHERE条件会删除所有行
*/DELETEFROM weather WHERE city = 'Hayward';/*
end
*/