如何获取id为0的mysql join结果

时间:2012-01-05 07:13:13

标签: php mysql

我有这个评论表,用户可以发表评论和访客,我可以获取这样的用户评论

SELECT `comments`.`user_id`, `comments`.`pubdate`,    `comments`.`comment`,
`comments`.`guest_name`,
`comments`.`id`, 
`users`.`username`, 

FROM (`comments`) 
JOIN `users` ON `comments`.`user_id` = `users`.`user_id` 
WHERE `item_id` = '64' AND `section` = 'blog'

问题是访客用户没有用户ID,因此他们的ID转为db为0所以它不显示,我如何显示用户和访客的评论?

4 个答案:

答案 0 :(得分:2)

您应该使用LEFT JOIN

SELECT `comments`.`user_id`, `comments`.`pubdate`,    `comments`.`comment`,
        `comments`.`guest_name`,
        `comments`.`id`, 
        `users`.`username`, 

FROM `comments`
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`user_id` 
WHERE `item_id` = '64' AND `section` = 'blog'

如果user没有匹配comments.user_id,则users.username将为NULL。

答案 1 :(得分:1)

使用左连接:

SELECT `comments`.`user_id`, `comments`.`pubdate`,    `comments`.`comment`,
`comments`.`guest_name`,
`comments`.`id`, 
`users`.`username`, 

FROM (`comments`) 
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`user_id` 
WHERE `item_id` = '64' AND `section` = 'blog'

答案 2 :(得分:0)

进行LEFT JOIN,而不是简单的。

答案 3 :(得分:0)


SELECT `comments`.`user_id`, `comments`.`pubdate`,    `comments`.`comment`,
        `comments`.`guest_name`, `comments`.`id`, `users`.`username`
FROM `comments`
LEFT JOIN `users` ON (`comments`.`user_id` = `users`.`user_id`) 
WHERE `item_id` = '64' AND `section` = 'blog'