2011-06-22 207 views
0

我有兩個我想合併爲一個的查詢。將兩個查詢合併爲一個

第一個看起來像這樣;

SELECT t.name, 
     t.score, 
     COUNT(m.user_id) AS memberCount 
     FROM team AS t, team_member AS m 
     WHERE t.team_id = '$id' AND m.team_id = '$id' 

第二個看起來像這樣;

SELECT COUNT(t.team_id) AS rank 
     FROM team AS t 
     WHERE t.score > (SELECT t.score 
           FROM team AS t 
           WHERE t.team_id = '$id') 

我懷疑JOIN會成爲解決方案的一部分,我只是不知道如何。 任何想法讚賞。

回答

1

你可以,例如,插入你的第二個查詢有權選擇第一個條款:

SELECT 
    t.name, 
    t.score, 
    (SELECT 
    COUNT(t.team_id) AS rank 
    FROM 
    team AS t 
    WHERE 
    t.score > (SELECT t.score FROM team AS t WHERE t.team_id = '$id') 
) as rank, 
    COUNT(m.user_id) AS memberCount 
FROM 
    team AS t, team_member AS m 
WHERE 
    t.team_id = '$id' AND m.team_id = '$id' 
+0

偉大的想法,謝謝! –

0

您可以使用UNION

SELECT t.name, 
    t.score, 
    COUNT(m.user_id) AS memberCount 
    FROM team AS t, team_member AS m 
    WHERE t.team_id = '$id' AND m.team_id = '$id' 
UNION 
SELECT COUNT(t.team_id) AS rank 
    FROM team AS t 
    WHERE t.score > (SELECT t.score 
          FROM team AS t 
          WHERE t.team_id = '$id') 
+0

我試過使用UNION,但由於列不匹配,我得到一個錯誤。 –

+0

嗯,哪些列不匹配? – Griwes