MySQL查询

时间:2015-08-07 14:15:21

标签: mysql join count group-by

我希望在一组两个日期内按类别计算我的所有项目。 我有一张主表:

项目

+-----+-------------+------------------+
| uid |    name     | project_category |
+-----+-------------+------------------+
|   1 | Testproject |                1 |
|   2 | Anothertest |                2 |
|   3 | Fietspomp   |                1 |
|   4 | Caramba     |                1 |
+-----+-------------+------------------+

其中的类别存储在 project_category

+-----+-------------+
| uid |    name     |
+-----+-------------+
|   1 | Automotive  |
|   2 | Hospitality |
|   3 | Other       |
+-----+-------------+

但是,我的日期存储在下表中。每个项目可以有更多的日期(班次)。我希望每个项目只找到最早的日期(班次):我需要过滤每个项目的开始日期(=第一班)。

project_shift

+-----+-------------+------------+
| uid | project_uid |    date    |
+-----+-------------+------------+
|   1 |           1 | 2015-05-03 |
|   2 |           2 | 2015-05-02 |
|   3 |           2 | 2015-06-04 |
|   4 |           1 | 2015-03-08 |
|   5 |           1 | 2015-08-08 |
+-----+-------------+------------+

我一直在寻找高低,但我的数量一直在变得混乱。这就是我试过的:

SELECT pc.name as category, p.name, count(p.uid)
FROM project p
INNER JOIN project_category pc ON pc.uid = p.project_category
INNER JOIN project_shift ps    ON ps.project_uid = p.uid AND ps.date BETWEEN "2015-01-01" AND "2015-08-08"
GROUP BY pc.uid

此外:

SELECT    pc.name as category, count(pc.uid) as amount
FROM      project p
LEFT JOIN project_category pc ON pc.uid = p.project_category
WHERE     (SELECT MIN(date) FROM project_shift ps WHERE ps.project_uid = p.uid LIMIT 1) BETWEEN :date_from AND :date_to
GROUP BY  pc.uid

最后一个接近,但仍然有29个项目太多。

我在这里做错了什么?

编辑:所需的结果如下(虚拟数据)

+-------------+--------+
|  category   | amount |
+-------------+--------+
| Automotive  |     70 |
| Hospitality |     22 |
| Other       |      2 |
+-------------+--------+

3 个答案:

答案 0 :(得分:1)

您还需要在组中的项目表中包含project_category:

SELECT pc.name as category,  count(p.project_category)
FROM project p, project_category pc, project_shift ps
where pc.uid = p.project_category
and ps.project_uid = p.uid
and ps.date BETWEEN '1/1/2015' and '8/8/2015'
group by pc.uid, p.project_category

应该这样做。

答案 1 :(得分:1)

您的查询似乎差不多。只有,你应该选择的project_category和应该外部连接的项目(例如获取零项目的类别)。因此,您希望按类别计算项目(即p.uid)。

然后你的LIMIT条款毫无意义。 MIN(日期)为您提供一条记录,其中包含项目的最短日期。这里不需要LIMIT条款。

SELECT    pc.name as category, count(p.uid) as amount
FROM      project_category pc 
LEFT JOIN project p ON p.project_category = pc.uid
WHERE     (SELECT MIN(date) FROM project_shift ps WHERE ps.project_uid = p.uid)
            BETWEEN :date_from AND :date_to
GROUP BY  pc.uid;

答案 2 :(得分:0)

试试这个:

SELECT    pc.name as category, count(pc.uid) as amount
FROM      project p
INNER JOIN project_category pc ON pc.uid = p.project_category
INNER JOIN
    (
        SELECT MIN(`date`) AS `date`, project_uid FROM project_shift 
        WHERE `date` BETWEEN :date_from AND :date_to
        GROUP BY project_uid
    ) AS ps ON (ps.project_uid = pc.uid) 
GROUP BY  pc.uid