php - 如何获取id为0的mysql连接结果

标签 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'

问题是 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/

相关文章:

SQL - 纬度/经度距离查询 - 如果距离 = 0,则不返回任何内容

php - 如何全局使CGridView使用 "raw"作为CDataColumn的默认类型?

mysql - Liquibase 给出 MySQL 语法错误,而 phpMyAdmin 没有

php - 如何在php和mysql中进行乘法运算

php - 为多个插入和更改表查询创建存储过程

PHP Foreach 问题?

php - 在另一个区域重用 PDO 查询 block 最佳实践

javascript - 在 JavaScript 中更改默认图像扩展名

php - 启动进程,从 ps 隐藏参数

php - 按最新条目分组并使用附加条件过滤掉