我试图从union all查询中获取两个计数值,然后将这两个值的总和组合起来,这样我就有了一个总数。目前的查询给了我2行数据,每个查询都是1行。
我如何更新下面的查询,使其只显示1行,其中包含2个查询的总数。
SELECT SUM(qty) as qty
FROM (
SELECT COUNT(f.unread) as qty
FROM users u, followers f
WHERE u.uid = f.follower AND f.uid = '605bb0e3d8fb16.55214369' AND f.unread = 'Y' GROUP BY f.unread
UNION ALL
SELECT COUNT(f.unread) as qty
FROM users u, comments f, subs s
WHERE u.uid = f.uid AND s.sid = f.sid AND s.uid = '605bb0e3d8fb16.55214369' AND f.uid <> '605bb0e3d8fb16.55214369' AND f.unread = 'Y' GROUP BY f.unread
) t
GROUP BY t.qty
提前感谢
尽量不要使用旧的
select something
from table1, table2, table3
where table1.something = table2.something
相反,请正确列出您的加入:
SELECT SUM(qty) as qty
FROM (
SELECT COUNT(f.unread) as qty
FROM users u
JOIN followers f ON u.uid = f.follower f.uid = '605bb0e3d8fb16.55214369' AND f.unread = 'Y'
UNION ALL
SELECT COUNT(f.unread) as qty
FROM users u
JOIN comments f ON u.uid = f.uid AND f.uid <> '605bb0e3d8fb16.55214369' AND f.unread = 'Y'
JOIN subs s ON s.sid = f.sid AND s.uid = '605bb0e3d8fb16.55214369'
) t
一旦你习惯了,新方法就会更容易遵循,尤其是在更大的查询中
如果愿意,可以将非表链接子句(即AND s.uid = '605bb0e3d8fb16.55214369'
(移到末尾的where子句,但为了可读性,我喜欢在联接本身中保留与表集相关的任何内容。这里讨论了一下:在JOIN或WHERE中设置条件并在联接中保留过滤器可以提高性能,但我不确定我们在说什么,我只是觉得这样更容易阅读和维护。
当没有GROUP BY时,聚合函数(如SUM(适用于所有行。因此,您只需移除外部GROUP BY即可对两个查询的结果求和。
内部的GROUP BY子句也是不需要的,尽管没有害处,因为在两个统一的查询中,每个查询中只有一个可能的f.read值。
或者,您可以简单地添加结果,而不是使用SUM/UNION:
SELECT (
SELECT COUNT(f.unread) as qty
FROM users u, followers f
WHERE u.uid = f.follower AND f.uid = '605bb0e3d8fb16.55214369' AND f.unread = 'Y'
) + (
SELECT COUNT(f.unread) as qty
FROM users u, comments f, subs s
WHERE u.uid = f.uid AND s.sid = f.sid AND s.uid = '605bb0e3d8fb16.55214369' AND f.uid <> '605bb0e3d8fb16.55214369' AND f.unread = 'Y'
);
因为只要表达式只返回一列和一行,就可以在表达式中使用带括号的子查询。