我有这个评论表,用户可以在其中发表评论以及访客,我可以像这样获取用户评论
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'
问题是 guest 用户没有用户ID,因此他们的ID作为0进入数据库,因此不显示,我如何显示用户和 guest 的评论?
最佳答案
您应该使用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'
如果 comments.user_id
没有匹配的 user
,则 users.username
将为 NULL。
关于php - 如何获取id为0的mysql连接结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8738888/