sql - SQL issue with RIGHT JOINS
问题描述
The following SQL query does exactly what it should do, but I don't know how to change it so it does what I need it to do.
SELECT
a.id AS comment_id, a.parent_comment_id, a.user_id, a.pid, a.comment, a.blocked_at, a.blocked_by, a.created_at, a.updated_at,
b.name, b.is_moderator, COUNT(IF(d.type = 1, 1, NULL)) AS a_count, COUNT(IF(d.type = 2, 1, NULL)) AS b_count
FROM
comments AS a
RIGHT JOIN
users AS b ON b.id = a.user_id
RIGHT JOIN
node_user AS c ON c.user = b.id
RIGHT JOIN
nodes AS d ON d.id = c.node
WHERE
a.pid = 999
GROUP BY
comment_id
ORDER BY
a.created_at ASC
It gets all comments belonging to a specific pid
, it then RIGHT JOINS
additional user data like name
and is_moderator
, then RIGHT JOINS
any (so called) nodes including additional data based on the user id
and node id
. As seen in the SELECT
, I count the nodes based on their type.
This works great for users that have any nodes
attached to their accounts. But users who don't have any, so whose id
doesn't exist in the node_user
and nodes
tables, won't be shown in the query results.
So my question:
How can I make it so that even users who don't have any nodes
, are still shown in the query results but with an a_count
and b_count
of 0
or NULL
.
解决方案
I'm pretty sure you want left joins not right joins. You also want to fix your table aliases so they are meaningful:
SELECT . . .
FROM comments c LEFT JOIN
users u
ON u.id = c.user_id LEFT JOIN
node_user nu
ON nu.user = u.id LEFT JOIN
nodes n
ON n.id = nu.node
WHERE c.pid = 999
GROUP BY c.id
ORDER BY c.created_at ASC;
This keeps everything in the first table, regardless of whether or not rows match in the subsequent tables. That appears to be what you want.
推荐阅读
- python - 防止表单文本字段中的 HTML 转义?
- php - 激活状态按钮前后的检查按钮
- r - 为什么 R 的 print 中的 'digits' 参数会改变一个值?
- android - 可以在一个 Android 应用中使用两个不同的 Firebase 项目,特别是崩溃分析、消息传递和性能扩展
- linux - 如何在 GNURadio Companion (Ubuntu) 上安装 NI USRP 2921?
- rust - 如何借用对本身位于选项内的 RefCell 内的东西的引用?
- javascript - 提交按钮冻结 chrome、safari 和 firefox 的不同行为
- php - 如何删除不存在的带有图像和mysql记录新闻的文件夹
- javascript - 分页无法正常工作 - Ngx-pagination
- java - 编写一个方法来读取包含 Int 和字符串的文件到 arraylist