MySQL左连接而不是等于

时间:2013-10-29 09:00:30

标签: php mysql join left-join

我搞乱了MySQL Query ...我想在另一个表中获取一些不存在某些值的表记录,但我不想使用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'

建议结果: (找到 analysis_id 不等于 1.0.1 tbl_analysis 中不存在的所有评论)

  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 个答案:

答案 0 :(得分:5)

试试这个

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.

答案 1 :(得分:5)

您正在LEFT JOIN表格上执行comments,但您已在comments表格中的其中一列(即WHERE 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'
;

答案 2 :(得分: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'

答案 3 :(得分:0)

您的选择别名错误。试试这个:

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'