2015-06-13 65 views
0

我有5個表我想從中選擇數據,但有時第5個表(名爲comment)將是空的。當發生這種情況時,我希望我的查詢爲該表中的值返回null,並且只返回其他值(第5個表包含用戶註釋,有時不存在)。mysql SELECT column only if if exists

這裏是我的查詢:

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。我不知道怎麼寫,只是爲了檢查這個,如果它在那裏,否則就忽略它。

感謝您的幫助

+1

使用連接(特別是'左JOIN') – h2ooooooo

回答

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;