我有一个表关注者和关注者计数..
想在一个存储过程中获得两者的计数..是否可以在同一个表上有两个具有不同 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)
最佳答案
为什么不使用 UNION ALL 触发这两个语句?
参见:http://dev.mysql.com/doc/refman/5.1/de/union.html
所以:
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
关于mysql - 同一个表上具有不同 where 子句的两个选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26229661/