Mysql - 连接查询的总计数结果

时间:2017-05-25 11:46:58

标签: mysql sql

我有用户,他们可以在一段时间内预订很多。每个预订可以有多个人。

查询可能如下所示:

SELECT users.*, 
(SELECT COUNT(person) FROM person_to_booking WHERE person_to_booking.booking = bookings.id) AS people_per_booking
FROM users
LEFT JOIN bookings ON users.id = bookings.user
GROUP BY users.id

这将返回一个结果,其中包含最后一次预订人数。如果我删除了GROUP BY,那么我会获得4行,每行都有正确的预订人数。

我需要有一行,SUM()COUNT(person)。我怎样才能做到这一点?

修改

表的结构如下:

Users

id | name 
---------
1  | Dave
2  | Bob

Bookings

id | user | company
-------------
1  | 1    | Big Group
2  | 1    | Big Group
3  | 2    | Small Company

Person to Bookings

id | person | bookings
----------------------
1  | 1      | 1
1  | 2      | 1
1  | 3      | 1
1  | 4      | 1
1  | 5      | 2
1  | 6      | 2

因此,用户可以预订,然后预订可以有很多人。

1 个答案:

答案 0 :(得分:0)

如果我理解正确

SELECT users.*,
SELECT SUM(cper) FROM (SELECT COUNT(person) as cper FROM person_to_booking WHERE person_to_booking.booking = bookings.id) AS people_per_booking
FROM users
LEFT JOIN bookings ON users.id = bookings.user
GROUP BY users.id