Mysql
給定一個包含班級和學生的表,需要找到學生的差異
我有 class_students 表,給定 2 個班級 ID,我需要找到學生的差異。這是我使用的 sql fiddle, http ://sqlfiddle.com/#!9/dba48e/11 這裡有任何幫助。
您可以使用
NOT IN
而不是 MINUS 運算符來獲得預期的結果,因為 MySQL 沒有 MINUS 運算符。SELECT a.student_id FROM `class_students` a WHERE a.class_id = '1' AND a.student_id NOT IN ( SELECT b.student_id FROM `class_students` b WHERE b.class_id = '2' )
或
LEFT JOIN
用作SELECT a.student_id FROM `class_students` a LEFT JOIN `class_students` b ON b.student_id = a.student_id AND b.class_id = '2' WHERE a.class_id = '1' AND b.student_id IS NULL
使用,例如
SELECT student_id FROM class_students GROUP BY student_id HAVING SUM(class_id = 1) > 0 AND SUM(class_id != 1) = 0
更多資訊是
SELECT student_id, GROUP_CONCAT(DISTINCT class_id) classes_in FROM class_students GROUP BY student_id HAVING COUNT(DISTINCT class_id) < ( SELECT COUNT(DISTINCT class_id) FROM class_students )
PS。建議 - 定義
(class_id, student_id)
(或按後向欄位順序)作為唯一/主索引 - 它將禁止重複記錄。