加入两个表后计数

时间:2018-12-18 13:33:00

标签: mysql join count

我有下表:

约会

id |    date    |   time
1  | 2018-12-02 | 10:00:00
2  | 2018-12-05 | 12:00:00
3  | 2018-12-12 | 16:00:00
4  | 2018-12-12 | 17:00:00
5  | 2018-12-13 | 09:00:00

约会服务

id | appointment_id | service_id
1  |        1       |     24
2  |        2       |     24
3  |        3       |     21
4  |        4       |     24
5  |        5       |     18

我想从约会表中搜索一个日期段,并从约会服务表中为每个service_id计数。

所以最终结果将是

service_id | times
     24    |   3
     21    |   1
     18    |   1

这是我到目前为止所做的

SELECT * FROM `appointment` a
INNER JOIN appointment_services s ON a.id = s.appointment_id
WHERE a.date BETWEEN '2018-12-10' AND '2018-12-18'

5 个答案:

答案 0 :(得分:1)

您很亲密:

select s.service_id, count(*) as times
from appointment_services s
join appintment a on a.id = s.appointment_id
where a.date between '2018-12-10' and '2018-12-18'
group by s.service_id

答案 1 :(得分:0)

您可以在下面尝试-使用count()聚合和分组依据

 SELECT s.service_id, count(*) as cnttimes
    FROM `appointment` a
    INNER JOIN appointment_services s ON a.id = s.appointment_id
    WHERE a.date BETWEEN '2018-12-10' AND '2018-12-18'
    group by s.service_id

答案 2 :(得分:0)

您必须使用service GROUP BY语句按service_id列对数据进行分组。例如:

SELECT s.service_id, 
       count(*) as times
FROM `appointment` a
INNER JOIN appointment_services s ON a.id = s.appointment_id
WHERE a.date BETWEEN '2018-12-10' AND '2018-12-18'
GROUP BY s.service_id

答案 3 :(得分:0)

我建议将appointment_services表联接到appointment上的子查询中,并限制所需的日期范围。即使没有匹配的约会,这也使我们能够保留所有服务值。

SELECT
    s.service_id,
    COUNT(a.id) AS times
FROM appointment_services s
LEFT JOIN
(
    SELECT id
    FROM appointment
    WHERE date BETWEEN '2018-12-10' AND '2018-12-18'
) a
    ON s.appointment_id = a.id
GROUP BY
    s.service_id;

enter image description here

Demo

请注意,我有意更改了service_id = 18的数据,以使它的单个约会 not 不在您想要的日期范围内。使用我建议的方法,我们仍然报告18的计数为零。直接进行内部联接将完全过滤掉18,并且它将出现在结果集中。

答案 4 :(得分:0)

http://sqlfiddle.com/#!9/1ad0f03/1

SELECT s.service_id, COUNT(*) 
FROM `appointment_services` s
LEFT JOIN  appointment a 
ON a.id = s.appointment_id
WHERE a.date BETWEEN '2018-12-10' AND '2018-12-18'
GROUP BY s.service_id

预期结果的问题是您的WHERE子句减少了几行,所以有效的结果是:

service_id COUNT(*)
18          1
21          1
24          1