SQL RIGHT JOINS 问题
SQL issue with RIGHT JOINS
下面的 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
它获取属于特定 pid
的所有评论,然后 RIGHT JOINS
其他用户数据,如 name
和 is_moderator
,然后 RIGHT JOINS
任何 (所谓的)节点包括基于 user id
和 node id
的附加数据。如 SELECT
中所示,我根据节点的类型对其进行计数。
这对于在其帐户上附加了任何 nodes
的用户来说非常有用。但是没有任何用户,因此 node_user
和 nodes
表中不存在 id
的用户将不会显示在查询结果中。
所以我的问题是:
我怎样才能做到这一点,即使没有任何 nodes
的用户仍然显示在查询结果中,但 a_count
和 b_count
为 0
或 NULL
.
我很确定你想要左连接而不是右连接。您还想修复您的 table 别名,使它们有意义:
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;
这会保留 firsttable 中的所有内容,而不管后续 table 中的行是否匹配。这似乎是你想要的。
下面的 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
它获取属于特定 pid
的所有评论,然后 RIGHT JOINS
其他用户数据,如 name
和 is_moderator
,然后 RIGHT JOINS
任何 (所谓的)节点包括基于 user id
和 node id
的附加数据。如 SELECT
中所示,我根据节点的类型对其进行计数。
这对于在其帐户上附加了任何 nodes
的用户来说非常有用。但是没有任何用户,因此 node_user
和 nodes
表中不存在 id
的用户将不会显示在查询结果中。
所以我的问题是:
我怎样才能做到这一点,即使没有任何 nodes
的用户仍然显示在查询结果中,但 a_count
和 b_count
为 0
或 NULL
.
我很确定你想要左连接而不是右连接。您还想修复您的 table 别名,使它们有意义:
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;
这会保留 firsttable 中的所有内容,而不管后续 table 中的行是否匹配。这似乎是你想要的。