连接两个表后计数

eni9jsuy  于 2021-06-15  发布在  Mysql
关注(0)|答案(5)|浏览(337)

我有以下表格:
约会

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

我想从约会表中搜索一个日期周期,并从约会服务表中计算每个服务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'
pokxtpni

pokxtpni1#

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
pbpqsu0x

pbpqsu0x2#

你很接近:

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
cidc1ykv

cidc1ykv3#

我建议你加入 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;

演示

注意,我故意更改了 service_id = 18 这样它的单个约会就不在你想要的日期范围内了。使用我建议的方法,我们仍然报告 18 计数为零。做一个笔直的内部连接会被过滤掉 18 完全,它会出现在结果集中。

hyrbngr7

hyrbngr74#

必须使用help group by语句按服务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
waxmsbnn

waxmsbnn5#

您可以在下面尝试使用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

相关问题