MySQL查询:相同question_id且Table2无对应记录的数据
查询Table1中Table2无对应记录的行
你的SQL问题出在JOIN条件的逻辑错误:你用OR把两种question_type的关联规则分开,这会让Table1里question_id=1、question_type=2的记录,错误地和Table2里question_id=1、question_type=1的记录建立关联,导致t2.completed不为NULL,自然查不到目标行。
以下是几种正确的写法:
方法1:修正LEFT JOIN关联条件
直接同时匹配question_id和question_type两个字段,确保只有完全对应的记录才会关联:
SELECT * FROM table1 t1 LEFT JOIN table2 t2 ON t1.question_id = t2.question_id AND t1.question_type = t2.question_type WHERE t2.completed IS NULL AND t1.question_id = 1
方法2:使用NOT EXISTS子查询
逻辑更直观,直接判断Table1的当前行在Table2中没有匹配记录:
SELECT * FROM table1 t1 WHERE t1.question_id = 1 AND NOT EXISTS ( SELECT 1 FROM table2 t2 WHERE t1.question_id = t2.question_id AND t1.question_type = t2.question_type )
方法3:使用NOT IN(慎用NULL场景)
当Table2的question_id和question_type都不会为NULL时,这种写法更简洁:
SELECT * FROM table1 t1 WHERE t1.question_id = 1 AND (t1.question_id, t1.question_type) NOT IN ( SELECT question_id, question_type FROM table2 )
内容的提问来源于stack exchange,提问作者Ahmed
相关产品推荐
相关产品推荐

