将两个查询合并为一个

时间:2011-06-22 09:01:21

标签: mysql

我有两个想要合并为一个的查询。

第一个看起来像这样;

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会成为解决方案的一部分,我只是不知道如何。 任何想法都赞赏。

2 个答案:

答案 0 :(得分:1)

例如,您可以将第二个查询权限插入第一个查询的SELECT子句:

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'

答案 1 :(得分: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')