我的问题的主题有点令人困惑,因为我已经没有足够的词来适应它的一般和技术描述了。
用不太专业的术语来说,我要具体完成的是:
List all churches and their corresponding booking status from a service they are offering with the following fields:
- 教会 ID AS
id
- 教会名称AS
name
- 他们提供的所有服务的
pending
状态计数 ASpendingCount
- 他们提供的所有服务的
完全预订
状态计数 ASbookedCount
关联表的结构如下:
教会
+---------+---------------+
| id(int) | name(varchar) |
+---------+---------------+
服务
+---------+---------------+---------------+
| id(int) | name(varchar) | churchId(int) |
+---------+---------------+---------------+
预订
+---------+-----------------+----------------+
| id(int) | status(varchar) | serviceId(int) |
+---------+-----------------+----------------+
到目前为止我得到的是这个,我完全不知道为什么它正在编译但会产生负面结果:
SELECT
churches.id,
churches.name,
pending.count AS pendingCount,
booked.count AS bookedCount
FROM
churches
INNER JOIN
services
ON
services.churchId = churches.id
LEFT JOIN
(SELECT
COUNT(bookings.id) AS `count`,
bookings.serviceId
FROM
bookings
WHERE
bookings.status = 'pending'
GROUP BY
bookings.serviceId)
AS pending
ON
pending.serviceId = services.id
LEFT JOIN
(SELECT
COUNT(bookings.id) AS `count`,
bookings.serviceId
FROM
bookings
WHERE
bookings.status = 'fully booked'
GROUP BY
bookings.serviceId)
AS booked
ON
booked.serviceId = services.id
示例输出
最佳答案
我会为此使用条件聚合。这是一种对满足特定值的行数求和的方法。在这种情况下,我们可以对 SUM(b.status = 'fullyBooked')
和 SUM(b.status = 'pending')
使用聚合并按教会分组 id
像这样:
SELECT c.id, c.name,
SUM(b.status = 'pending') AS pendingCount,
SUM(b.status = 'fully booked') AS bookedCount
FROM bookings b
RIGHT JOIN services s ON s.id = b.serviceId
RIGHT JOIN churches c ON c.id = s.churchid
GROUP BY c.id;
重申一下,通过使用 SUM(condition)
并按某个 id
值分组,您计算的是该 条件为真的次数id
值。
编辑:
我已将 RIGHT OUTER JOIN
添加到此查询中,这样也将返回没有任何预订的教堂。
关于MySQL 列出单个表中的一些字段并计算来自另一个表的所有特定字段引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33337836/