0

这是两个非常相似的查询。它们之间的区别在于,在第二个查询中,我添加了名为 ng2s3_map 的新表,并且我只需要从那里获取一列。问题是第一个查询一直根据需要工作,但不输出 lik 列,第二个查询只有在表 ng2s3_map 中有行时才有效,否则它什么也不输出。如何更改第二个查询,因此无论 ng2s3_map 表中是否有行,它都会输出结果。(我添加 2 个表的唯一原因是为了更好地解释我的问题)。

第一个查询:

SELECT ng2s3_content.ID, ng2s3_similar.similar_ID, ng2s3_similar.up, ng2s3_similar.down, similar_articles.Title AS SimilarTitle, similar_articles.image AS image
FROM ng2s3_content
JOIN ng2s3_similar ON ng2s3_content.ID = ng2s3_similar.ID
JOIN ng2s3_content similar_articles ON ng2s3_similar.Similar_ID = similar_articles.ID
WHERE ng2s3_content.ID =4764

第二个查询:

SELECT ng2s3_content.ID, ng2s3_similar.similar_ID, ng2s3_similar.up, ng2s3_similar.down, ng2s3_map.similar_id, ng2s3_map.vote_id, ng2s3_map.lik, similar_articles.Title AS SimilarTitle, similar_articles.image AS image
FROM ng2s3_content
JOIN ng2s3_similar ON ng2s3_content.ID = ng2s3_similar.ID
JOIN ng2s3_content similar_articles ON ng2s3_similar.Similar_ID = similar_articles.ID
JOIN ng2s3_map ON ng2s3_map.similar_id = ng2s3_similar.similar_ID
AND ng2s3_map.vote_id = ng2s3_content.ID
WHERE ng2s3_content.ID =4764
4

1 回答 1

1

如果是这种情况,那么您需要使用LEFT JOIN而不是INNER JOIN

SELECT  ng2s3_content.ID, 
        ng2s3_similar.similar_ID, 
        ng2s3_similar.up, 
        ng2s3_similar.down, 
        ng2s3_map.similar_id, 
        ng2s3_map.vote_id, 
        ng2s3_map.lik, 
        similar_articles.Title AS SimilarTitle, 
        similar_articles.image AS image
FROM    ng2s3_content
        INNER JOIN ng2s3_similar 
            ON ng2s3_content.ID = ng2s3_similar.ID
        INNER JOIN ng2s3_content similar_articles 
            ON ng2s3_similar.Similar_ID = similar_articles.ID
        LEFT JOIN ng2s3_map 
            ON  ng2s3_map.similar_id = ng2s3_similar.similar_ID AND 
                ng2s3_map.vote_id = ng2s3_content.ID
WHERE   ng2s3_content.ID = 4764

要进一步了解有关联接的更多信息,请访问以下链接:

于 2013-03-18T08:07:23.903 回答