MySQL 列出单个表中的一些字段并计算来自另一个表的所有特定字段引用

标签 mysql subquery left-join inner-join

我的问题的主题有点令人困惑,因为我已经没有足够的词来适应它的一般和技术描述了。

用不太专业的术语来说,我要具体完成的是:

List all churches and their corresponding booking status from a service they are offering with the following fields:

  • 教会 ID AS id
  • 教会名称AS name
  • 他们提供的所有服务的pending 状态计数 AS pendingCount
  • 他们提供的所有服务的完全预订状态计数 AS bookedCount

关联表的结构如下:

教会

+---------+---------------+
| 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

示例输出

enter image description here

最佳答案

我会为此使用条件聚合。这是一种对满足特定值的行数求和的方法。在这种情况下,我们可以对 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/

相关文章:

java - hibernate 不进行急切获取(使用获取 ="join"和惰性 ="false")

mysql - 连接将结果限制为连接表,无需子选择

mysql - SQL: N-N Select * from table1 并检测是否与特定用户 ID 的另一个存在关系

MySQL在三张表上写连接

matlab - MATLAB 中元胞数组的左连接

MYSQL无法计算日期范围内特定值的出现次数

mysql - 如何选择mysql中具有不同日期格式的日期列?

codeigniter - CodeIgniter 中 Join 中的子查询

pagination - 学说2 : Limiting with Left Joins/Pagination - Best Practice

mysql - LEFT OUTER JOIN 没有显示所有行?