加入多个select语句的结果

时间:2012-03-16 09:05:35

标签: mysql join

我想水平合并以下三个select语句的结果。我尝试使用连接,但不知道如何继续,因为它也涉及COUNT和GROUP BY。

SELECT DATE(created_at) as date,COUNT(*) as countd1 FROM b_users WHERE last_loggedin_at < DATE_ADD(created_at,INTERVAL 1 DAY) GROUP BY DATE(created_at)
SELECT DATE(created_at) as date,COUNT(*) as countd2 FROM b_users WHERE last_loggedin_at < DATE_ADD(created_at,INTERVAL 2 DAY) GROUP BY DATE(created_at)
SELECT DATE(created_at) as date,COUNT(*) as countd3 FROM b_users WHERE last_loggedin_at < DATE_ADD(created_at,INTERVAL 3 DAY) GROUP BY DATE(created_at)

个人结果将是

date        countd1
2011-12-01   100
2011-12-02   120
2011-12-03   130

date        countd2
2011-12-01   200
2011-12-02   220
2011-12-03   230

date        countd3
2011-12-01   300
2011-12-02   320
2011-12-03   330

但是我想合并它们以便我得到以下结果

date        countd1    countd2    countd3
2011-12-01   100        200        300
2011-12-02   120        220        320
2011-12-03   130        230        330

我该怎么做?

是否可以执行类似下面的查询

SELECT a, COUNT(b where condition), COUNT(c where condition) FROM table GROUP BY a

更新

biziclop提供了很好的工作

SELECT DATE(created_at) AS date,
SUM(last_loggedin_at < DATE_ADD( created_at,INTERVAL 1 DAY )) AS countd1,
SUM(last_loggedin_at < DATE_ADD( created_at,INTERVAL 2 DAY )) AS countd2,
SUM(last_loggedin_at < DATE_ADD( created_at,INTERVAL 3 DAY )) AS countd3
FROM b_users GROUP BY DATE(created_at)

解决了,谢谢! :)

1 个答案:

答案 0 :(得分:0)

在MySQL中,如果为真,则比较结果为1,如果为假,则为0,因此您可以SUM()

SELECT
  DATE(created_at) AS date,
  SUM( last_loggedin_at < DATE_ADD( created_at,INTERVAL 1 DAY )) AS countd1,
  SUM( last_loggedin_at < DATE_ADD( created_at,INTERVAL 2 DAY )) AS countd2,
  SUM( last_loggedin_at < DATE_ADD( created_at,INTERVAL 3 DAY )) AS countd3,
FROM b_users
GROUP BY DATE(created_at)