3

我搞砸了 MySQL 查询...我想获取另一个表中不存在的具有某些值的表记录,但我不想使用 NOT IN 操作。然后,我尝试使用 LEFT JOIN 来显示不匹配的数据。但是,它显示空结果:

tbl_comment

comment_id | comment_message
----------------------------
1_1        | some text1...
1_2        | some text2...
1_3        | some text3...
2_1        | some text4...
2_2        | some text5...
2_3        | some text6...

tbl_analysis

analysis_id | analysis_message_id
----------------------------
1.0.1       | 1_1
1.0.1       | 1_2
1.0.1       | 2_1
1.0.2       | 1_3
1.0.3       | 2_2

我的错误查询(空结果):

SELECT comments.* ,
       analysis.*
FROM tbl_comment as comments

LEFT JOIN tbl_analysis as analysis

ON comments.comment_id = analysis.analysis_message_id

WHERE analysis.analysis_id != '1.0.1'

Suggested Result: (在tbl_analysis中找到所有analysis_id不等于1.0.1或不存在的评论)

  comment_id  | comment_message | analysis_id | analysis_message_id
    ----------------------------------------------------------------
    1_3        | some text3...   | 1.0.2       | 1_3
    2_2        | some text5...   | 1.0.3       | 2_2
    2_3        | some text6...   | NULL        | NULL

感谢您的大力帮助...

4

4 回答 4

6

您正在对表执行 a ,但您已LEFT JOINcomments表中的一列上包含谓词,commentsWHERE analysis.analysis_id != '1.0.1'。这将否定你的LEFT JOIN. 试试这个

SELECT comments.* ,
       analysis.*
FROM tbl_comment as comments
LEFT JOIN tbl_analysis as analysis
ON comments.comment_id = analysis.analysis_message_id AND analysis.analysis_id != '1.0.1'
;
于 2013-10-29T09:05:10.540 回答
5

Try this

SELECT comments.* , analysis.*
FROM tbl_comment as comments
LEFT JOIN tbl_analysis as analysis
ON comments.comment_id = analysis.analysis_message_id
WHERE analysis.analysis_id IS NULL
//IS NULL OR IS NOT NULL according to you requirement.
于 2013-10-29T09:03:53.163 回答
1

请尝试此代码可能会起作用。

SELECT *

FROM tbl_comment as c

right JOIN tbl_analysis as a ON c.comment_id = a.analysis_message_id

WHERE a.analysis_id != '1.0.1'
于 2013-10-29T09:45:00.413 回答
0

Your select alias is wrong. Try this:

SELECT comment.* ,
       analysis.*

FROM tbl_comment as comments

LEFT JOIN tbl_analysis as analysis ON comments.comment_id = analysis.analysis_message_id

WHERE analysis.analysis_id != '1.0.1'
于 2013-10-29T09:03:54.690 回答