[英]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.以下 SQL 查询正是它应该做的,但我不知道如何改变它,所以它做了我需要它做的事情。
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
.它获取属于特定
pid
的所有评论,然后RIGHT JOINS
附加用户数据,如name
和is_moderator
,然后RIGHT JOINS
任何(所谓的)节点,包括基于user id
和node id
的附加数据。 As seen in the SELECT
, I count the nodes based on their type.如
SELECT
中所见,我根据节点类型计算节点。
This works great for users that have any nodes
attached to their accounts.这对于将任何
nodes
附加到其帐户的用户来说非常有用。 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.但是没有任何用户,因此其
id
不存在于node_user
和nodes
表中的用户,将不会显示在查询结果中。
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
.我怎样才能做到这一点,即使没有任何
nodes
的用户仍然显示在查询结果中,但a_count
和b_count
为0
或NULL
。
I'm pretty sure you want left join s not right join s.我很确定你想要left join s 而不是right join s。 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.
这似乎是你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.