将这两个查询组合成一个JOIN?

时间:2012-03-15 14:20:37

标签: mysql join

这两个查询有效:

SELECT
u.id,
u.email,
COUNT(*) as Current
FROM
users u,
rounds cur
WHERE
cur.user = u.id
AND u.email = 'foo@foo.com'
GROUP BY cur.user;

SELECT
u.id,
u.email,
COUNT(*) as old
FROM
users u,
rounds__20120311_010951 old
WHERE
old.user = u.id
AND u.email = 'foo@foo.com'
GROUP BY old.user;

但我真的想这样做:

SELECT
u.id,
u.email,
COUNT(old.*) as March11,
COUNT(cur.*) as Current
FROM
users u,
rounds cur,
rounds__20120311_010951 old
WHERE
old.user = u.id
AND cur.user = u.id
AND u.email = 'foo@foo.com'
GROUP BY old.user, cur.user

我认为语法错误来自此COUNT(。*),但我不确定。

是否可以组合这些查询?

3 个答案:

答案 0 :(得分:2)

使用GROUP BY u.id, u.email。然后,在您的选择中,使用COUNT(old.id)COUNT(cur.id)

答案 1 :(得分:1)

您也可以使用此查询 -

SELECT
  u.id,
  old.cnt as March11,
  cur.cnt as Current
FROM
  users u
LEFT JOIN (SELECT user, COUNT(*) cnt FROM rounds GROUP BY user) cur
  ON u.id = cur.user
LEFT JOIN (SELECT user, COUNT(*) cnt FROM rounds__20120311_010951 GROUP BY user) old
  ON u.id = old.user
 GROUP BY
   u.id

LEFT JOIN将显示users表中的(所有)记录以及来自两个连接表的所有相关记录。

答案 2 :(得分:1)

也许它看起来像:

SELECT
  u.id,
  u.email,
  COUNT(old.user) as March11,
  COUNT(cur.user) as Current
FROM users u
LEFT JOIN rounds cur ON cur.user=u.id
LEFT JOIN rounds__20120311_010951 old ON old.user=u.id
WHERE u.email = 'foo@foo.com'
GROUP BY u.id;