MySql从两个表中选择聚合

时间:2011-05-18 14:37:30

标签: mysql sql select

previous question中,我问过如何根据三个表格返回每个用户通过的最新测试的日期,用户测试通行证

|--------|---------|---------|---------|---------|---------|
|User    |Test A   |Test B   |Test C   |Test D   |Test E   |
|--------|---------|---------|---------|---------|---------|
|James   |Null     |6/3/11   |Null     |Null     |4/3/11   |
|Mark    |Null     |1/4/11   |8/5/11   |23/5/10  |Null     |
|--------|---------|---------|---------|---------|---------|

建议以下查询:

select
  u.username,
  max(case when testid = 1 then datetaken else null end) as A,
  max(case when testid = 2 then datetaken else null end) as B,
  max(case when testid = 3 then datetaken else null end) as C,
  max(case when testid = 4 then datetaken else null end) as D,
  max(case when testid = 5 then datetaken else null end) as E
from users as u left join passes as p on u.userid = p.userid
group by u.userid

事实证明,在我的实际场景中,我有两个Tests表(比如TestsX包含测试A,B和C以及TestsY包含测试D和E)和两个相应的pass表(比如PassesX和PassesY)。

这是必需的,因为表具有不同的结构。但是,为了简单起见,我们假设它们是相同的。它们都链接到同一个Users表。请您告诉我如何相应地调整上面的select命令,以获得相同的输出(一个表中的所有内容)?

也许这可以用子查询和联合实现,但我不知道怎么做?

非常感谢(我希望这是有道理的)。

2 个答案:

答案 0 :(得分:1)

SELECT
  u.UserName,
  px.TestA,
  px.TestB,
  px.TestC,
  py.TestD,
  py.TestE
FROM Users u
  LEFT JOIN (
    SELECT
      UserId,
      MAX(CASE TestId WHEN 1 THEN DateTaken ELSE NULL END) AS TestA,
      MAX(CASE TestId WHEN 2 THEN DateTaken ELSE NULL END) AS TestB,
      MAX(CASE TestId WHEN 3 THEN DateTaken ELSE NULL END) AS TestC
    FROM PassesX
    GROUP BY UserId
  ) px ON u.UserId = px.UserId
  LEFT JOIN (
    SELECT
      UserId,
      MAX(CASE TestId WHEN 4 THEN DateTaken ELSE NULL END) AS TestD,
      MAX(CASE TestId WHEN 5 THEN DateTaken ELSE NULL END) AS TestE,
    FROM PassesY
    GROUP BY UserId
  ) py ON u.UserId = py.UserId

答案 1 :(得分:0)

select   u.username,   
max(case when px.testid = 1 then px.datetaken else null end) as A,   
max(case when px.testid = 2 then px.datetaken else null end) as B,   
max(case when px.testid = 3 then px.datetaken else null end) as C,   
max(case when py.testid = 4 then py.datetaken else null end) as D,   
max(case when py.testid = 5 then py.datetaken else null end) as E 
from (users as u left join passesX as px on u.userid = px.userid)
      LEFT JOIN passesY as py on u.userid = py.userid) 
group by u.userid