Vai*_*ool 0 mysql sql sql-server stored-procedures
我有一个表跟随者和以下计数..
想要在一个存储过程中得到两者的计数..是否可以在同一个表上有两个具有不同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)
;
Run Code Online (Sandbox Code Playgroud)
我的选择查询
(select count(*) as following_count from table1 where val2=26)
(select count(*) as follower_count from table1 where val3=26)
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
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
Run Code Online (Sandbox Code Playgroud)
为什么不使用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
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5185 次 |
| 最近记录: |