練習MySQL聯表查詢時遇到這樣一道題
- 問題: 查詢"生物課程"比"物理課程"成績高的所有學生的相關信息
- 出錯指令:

1 SELECT student.sid AS '學號', student.sname AS '姓名', course.cname AS '課程', score.num AS '成績'
2 FROM student INNER JOIN course INNER JOIN score 3 ON student.sid=score.student_id AND course.cid=score.course_id AND course.cid=2
4 WHERE score.num < (SELECT score.num FROM course INNER JOIN score ON course.cid=score.course_id AND course.cid=1);
- 報錯信息:
ERROR 1242 (21000): Subquery returns more than 1 row
- 報錯信息翻譯:
子查詢返回超過1行
- 分析與解決方法:
1. 在重復寫入時會出現這種問題, 可通過去掉重復數據解決
- 通過在寫入時加邏輯判斷或者外鍵防止數據重復寫入
2. 利用IN、SOME、ANY、ALL關鍵字進行限制
- 報錯信息出自子查詢, 因此需要對子查詢涉及指令進行條件修改
- 最終解決指令:

1 SELECT student.sid AS '學號', student.sname AS '姓名', course.cname AS '課程', score.num AS '成績' 2 FROM student INNER JOIN course INNER JOIN score 3 ON student.sid=score.student_id AND course.cid=score.course_id AND course.cid=2 4 WHERE score.num < ANY(SELECT score.num FROM course INNER JOIN score ON course.cid=score.course_id AND course.cid=1);
補充
子查詢就是指在一個SELECT語句中嵌套另一個SELECT語句
IN、SOME、ANY、ALL都是子查詢涉及的關鍵詞
- ANY可與= (>, >=, <, <=, <>)結合使用,分別表示等於(大於, 大於等於, 小於, 小於等於, 不等於)其中的任何一個數據
-- ANY關鍵字必須與一個比較操作符一起使用
-- ANY關鍵詞可以理解為"對於子查詢返回的列中的任一數值, 如果比較結果為True, 則返回True"
- ALL可與= (>, >=, <, <=, <>)結合使用,分別表示等於(大於, 大於等於, 小於, 小於等於, 不等於)其中的所有數據
-- ALL關鍵字必須與一個比較操作符一起使用
-- ALL關鍵詞可以理解為"對於子查詢返回的列中的所有值, 如果比較結果為True, 則返回True"
- 關鍵詞IN 與關鍵詞組合"=ANY"作用相同

1 SELECT s1 2 FROM t1 3 WHERE s1 =ANY(SELECT s1 FROM t2); 4 -- 效果等同 5 SELECT s1 6 FROM t1 7 WHERE s1 IN(SELECT s1 FROM t2);
- NOT IN 與 "<>ALL"用法與作用相同

1 SELECT s1 2 FROM t1 3 WHERE s1 <>ANY(SELECT s1 FROM t2); 4 -- 效果等同 5 SELECT s1 6 FROM t1 7 WHERE s1 NOT IN(SELECT s1 FROM t2);
- SOME相當於ANY的別名

1 SELECT s1 FROM t1 WHERE s1 <> ANY(SELECT s1 FROM t2); 2 -- 效果等同 3 SELECT s1 FROM t1 WHERE s1 <> SOME(SELECT s1 FROM t2);
-- 在理解上SOME較ANY更容易解釋, 如上例子中涉及關鍵詞SOME的指令可以解釋為"表t1中有部分s1與表t2中的s1不相等", 涉及關鍵詞ANY的指令解釋為"表t1中的s1與表t2中的s1不全部相等"