2014-10-07 71 views
0

條款我有一個表的追蹤者和追蹤數選擇查詢..兩次與不同的地方在同一個表

想利用這兩者的數量在一個存儲過程..是有可能有不同的兩個選擇查詢在同一張桌子上的條件可能?

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) 

SQL FIDDLE LINK

回答

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 
+0

我認爲這會爲我工作 – 2014-10-07 06:30:39

3

你爲什麼不使用火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 
+0

試過工作 – 2014-10-07 06:27:45

+0

解釋什麼是行不通的。 – YvesR 2014-10-07 06:28:21

+0

不要在兩行..我想在兩列。 – 2014-10-07 06:29:30

0

只需添加分號您的語句......

(select count(*) as following_count from table1 where val2=26); 

(select count(*) as follower_count from table1 where val3=26); 
相關問題