本篇用于总结一些巧妙的sql语句,供自己不断翻看。
(1)求所有部门之前的比赛组合。
一个team表,表中有一个字段为name(部门名称),一共有5条记录,分别为1,2,3,4,5;对应5个部门,现在5个部门进行比赛用一条sql显示所有可能的比赛组合。
解:select a.name,b.name from team a, team b where a.ame<b.name;
(2)用一条sql语句查询出每门课都大于80分的学生姓名
两种思路:
a.查出有科目分数小于等于80的人,然后排除
select distinct name from table where name not in(select distinct name from table where fenshu<=80)
b.分组查询最小分数大于80的人
select name from (select name ,min(fenshu) score from table group by name) where score>80;
(3)每个月的发生额都比101科目多的科目
用sql实现从TestDB数据表中查出所有月份的发生额都比101科目相应月份的发生额高的科目。请注意:TestDB中有很多科目,都有1-12月份的发生额。AccID:科目代码,Occmonth:发生额月份,DebitOccur:发生额。
解:具体实现不写了,与第(2)题中的第一个思路一致
(4)显示文章标题、发帖人、最后回复时间(评论的)
表:id、title、postuser、postdate、parentid
解:select a.title,a.postuser,(select max(postdate) from table where parentid=a.id) reply from table a where a.parentid=null;
注意的是:子查询可以用在选择列中,也可以用在where的比较条件中,还可以用于from从句中
待续~~