MySQL中几个表和操作的SQL请求

时间:2014-01-14 11:57:58

标签: php mysql sql database

我有以下3个表:单位,阶段,统计数据。

      unit                      stage
+----+--------+   +----+-------+---------------------+
| id | status |   | id |unit_id|        date         |
+----+--------+   +----+-------+---------------------+
|  1 |      2 |   |  1 |     2 | 2013-11-22 00:00:00 |
|  2 |      3 |   |  2 |     2 | 2013-11-26 12:00:00 |
|  3 |      3 |   |  3 |     3 | 2013-10-11 00:00:00 |
|  4 |      0 |   |  4 |     1 | 2013-12-29 00:00:00 |
+----+--------+   +----+-------+---------------------+

                     stats
+----+----------+---------------------+-------+
| id | stage_id |        date         | clicks|
+----+----------+---------------------+-------+
|  1 |        1 | 2013-11-22 00:00:00 |    10 |
|  2 |        1 | 2013-11-23 00:00:00 |    20 |
|  3 |        1 | 2013-11-24 00:00:00 |    25 |
|  4 |        2 | 2013-11-26 00:00:00 |    15 |
|  5 |        2 | 2013-11-27 12:00:00 |    21 |
|  6 |        3 | 2013-12-29 00:00:00 |     8 |
+----+----------+---------------------+-------+

我需要一个请求,它会产生以下响应:

+---------+---------------------+-----------------------+
| unit.id |   stage.min.date    | sum(stats.max.clicks) |
+---------+---------------------+-----------------------+
|       2 | 2013-11-22 00:00:00 |                    46 |
|       3 | 2013-12-29 00:00:00 |                     8 |
+---------+---------------------+-----------------------+

遵守以下规则:

1)unit.id - 仅显示unit.status=3

的单位

2)stage.min.date - 对应stage.date

的最小unit_id

3)sum(stats.max.clicks) - stats.clicks的总和,其中每个stage_id的最大点数与相应的unit_id相关联。在我的示例中,46 = 25(stage_id=1)+ 21(stage_id=2

问题在于min.date和点击总和 - 我不知道如何在一个查询中获取它。使用PHP代码和几个请求肯定不是问题。

Schema in SQL Fiddle

提前致谢。

1 个答案:

答案 0 :(得分:1)

我只是问自己,为什么我这样做?你的例子共鸣有一个错误,与你的小提琴不符......但是:

SELECT
  cc.unit_id, MIN(cc.date) as stage_min_date , SUM(dd.clicks) as stats_max_clicks
FROM
  stage cc
LEFT JOIN (
  SELECT
    bb.stage_id, bb.clicks
  FROM
    stats bb LEFT JOIN (
      SELECT id, stage_id, MAX(date) AS max_date
      FROM stats
      GROUP BY stage_id
    ) aa
  ON
    aa.max_date = bb.date
  WHERE
    aa.max_date IS NOT NULL
) dd
ON cc.id = dd.stage_id
LEFT JOIN unit ee 
ON ee.id = cc.unit_id
WHERE ee.status = 3
GROUP BY cc.unit_id

...