mysql SELECT列只有存在

时间:2015-06-13 17:13:05

标签: mysql

我有5个表我想从中选择数据,但有时第5个表(命名注释)将为空。当发生这种情况时,我希望我的查询为该表中的值返回null,并且只返回其他值(第5个表包含用户注释,有时没有)。

这是我的问题:

SELECT articles.title, articles.posted, articles.body, authors.name, authors.img, authors.bio, comment.user_id, comment.text, comment.article_id, GROUP_CONCAT(categories.cat_name) AS cat_name
FROM articles, authors, categories, article_categories, comment 
WHERE articles.author_id = authors.id
AND articles.id = article_categories.article_id
AND article_categories.category_id = categories.id
AND articles.id = comment.article_id
AND title LIKE :title;

:title来自PDO,与此无关。

问题来自AND articles.id = comment.article_id。我不知道怎么写它只是为了检查它,如果它在那里,否则忽略它。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您应该使用proper join syntax,在这种情况下,而不是INNER JOIN使用LEFT JOIN作为评论表:

SELECT articles.title, articles.posted, articles.body, authors.name, authors.img, authors.bio, comment.user_id, comment.text, comment.article_id, GROUP_CONCAT(categories.cat_name) AS cat_name
FROM articles INNER JOIN authors ON articles.author_id = authors.id
INNER JOIN article_categories ON articles.id = article_categories.article_id
INNER JOIN categories ON article_categories.category_id = categories.id
LEFT JOIN comment ON articles.id = comment.article_id
WHERE title LIKE :title;

答案 1 :(得分:0)

你应该使用左/右连接来做到这一点。

[...]
select *
from articles a
  left join comments c
    on a.id = c.article_id
[...]

要了解有关联接的更多信息: http://blog.codinghorror.com/a-visual-explanation-of-sql-joins

相关问题