我有一个表跟随者并且跟随计数..
想要在一个存储过程中得到两者的计数..是否可以在同一个表上有两个具有不同where条件的选择查询?
CREATE TABLE Table1
([val1] int, [val2] int, [val3] int, [val4] int, other int)
;
INSERT INTO Table1
([val1], [val2], [val3], [val4], other)
VALUES
(1, 26, 13, 1, 1),
(2, 13, 26, 1, 1),
(3, 10, 26, 1, 1),
(4, 26, 13, 1, 1),
(5, 14, 26, 1, 1)
;
我选择查询
(select count(*) as following_count from table1 where val2=26)
(select count(*) as follower_count from table1 where val3=26)
答案 0 :(得分:5)
你可以这样做:
SELECT
SUM(CASE WHEN val2=26 THEN 1 ELSE 0 END) AS following_count,
SUM(CASE WHEN val3=26 THEN 1 ELSE 0 END) AS follower_count
FROM
table1
答案 1 :(得分:4)
为什么不使用UNION ALL激活这两个语句?
请参阅:http://dev.mysql.com/doc/refman/5.1/de/union.html
SO:
SELECT COUNT(*) AS following_count FROM table1 WHERE val2=26
UNION ALL
SELECT COUNT(*) AS following_count FROM table1 WHERE val3=26
在1个查询中返回两行,包含2个数字。
在两列中执行此操作:
SELECT
(SELECT COUNT(*) AS following_count FROM table1 WHERE val2=26) col1
, (SELECT COUNT(*) AS following_count FROM table1 WHERE val3=26) col2
答案 2 :(得分:0)
只需在你的陈述中添加分号......
(select count(*) as following_count from table1 where val2=26);
(select count(*) as follower_count from table1 where val3=26);