1.有一张shop表,有三个字段article,author,price,选出每个author的price的最高的纪录。(要包含所有字段)
解法一:使用相关子查询:
SELECT article,author,price
FROM shop s1
WHERE price = (SELECT MAX(s2.price)FROM shop s2 WHERE s1.author=s2.author );
解法二:使用非相关子查询:
SELECT article,s1.author,s1.price
FROM shop s1
JOIN(SELECT author,MAX(price) AS price
FROM shop
GROUP BY author) AS s2
ON s1.author=s2.author AND s1.price=s2.price;
由于子查询在有些时候,效率会很低,所以最后提供的方法是用LEFT JOIN语句。
解法三:使用LEFT JOIN 语句
SELECE s1.article,s1.author,s1.price
FROM shop s1
LEFT JOIN shop s2
ON s1.author=s2.author AND s1.price<s2.price
WHERE s2.article IS NULL;
上述LEFT JOIN(左连接)语句的原理是:
当 s1.price 是当前author的最大值时,就没有 s2.price比它还要大,所以此时s2的rows的值都会是NULL。
2.两个表结构如下:
①如果学号的前两位表示年纪,要查找98级女生的姓名,请写出相应SQL语句。
第一种:
SELECT s.Sc_name scoreName
FROM score AS s
WHERE s.Sc_number LIKE '98%'
第二种:
SELECT s.Sc_name scoreName
FROM score AS s
WHERE left(s.Sc_number,2)='98'
②要查找所有需要补考(小于60分)的学生姓名和课程的名字和成绩,请写出相应SQL语句。
SELECT s.Sc_name,c.Co_name,s.Sc_score
FROM score AS s,course AS c
WHERE s.Sc_courseid=c.Coid AND s.Sc_score<60
③查询每个学生需要补考(小于60分)的课程的平均分,并以平均分排序。
SELECT s.Sc_name,AVG(s.Sc_score)
FROM score AS s,course AS c
WHERE s.Sc_courseid=c.Coid AND s.Sc_score<60
GROUP BY s.Sc_name
ORDER BY AVG(s.Sc_score)