按多个条目分组

时间:2016-12-08 07:26:41

标签: mysql sql mysqli

数据库有几个表:

  • 预订
  • 指南

现在每个巡演都可以进行 n 预订,每位导游都可以进行 n 巡回演出。但是,在我的主页上,我只想显示5个游览的列表,每个指南限制为1个游览。但是,如果我从左连接中取出预订,我需要按“tourId”进行分组,但另一方面我还需要按“tourGuideId”进行分组,以限制为1.如果我 GROUP BY tourGuideId 它显示每个指南只有一个巡回演出,但是左边连接会出现问题并显示预订,尽管没有。如果我 GROUP BY tourId ,它适用于LEFT JOIN,但不适用于每个指南的限制1。

以下是简单查询:

SELECT f.*, SUM(b.bookingSeats) AS bookings
FROM tours AS f 
LEFT JOIN bookings AS b ON f.tourId = b.bookingTourId 
WHERE f.tourActive = '1'
GROUP BY f.tourGuideId
ORDER BY f.tourId DESC 
LIMIT 5

如何进行?

编辑1:一个简单的“GROUP BY f.tourGuideId,f.tourId”不起作用。它使LEFT JOIN工作,但不限于每个指南1个结果。

编辑2:示例结果应为:

tourId, tourGuideId, tourTitle, tourDate, tourActive, bookings
5, 1, 'Hello World', '2016-12-01 08:00:00', 1, NULL
9, 3, 'Tour Paris', '2017-03-01 08:00:00', 1, 3

预订表结构:

bookingId, bookingStatus, bookingUserId, bookingDate, bookingPaid

巡回表结构:

tourId, tourGuideId, tourTitle, tourDate, tourActive

1 个答案:

答案 0 :(得分:1)

从查询开始,获取每个指南的最新信息,如SQL Select only rows with Max Value on a Column

所示

然后将其加入子查询,该子查询获得每个指南的总预订量。

SELECT f.*, bookings
FROM tours AS f
JOIN (SELECT MAX(tourId) AS maxTourId
      FROM tours
      GROUP BY tourGuideId) AS f1
ON f.tourId = f1.maxTourId
JOIN (
    SELECT tourGuideId, SUM(b.bookingSeats) AS bookings
    FROM tours AS f
    LEFT JOIN bookings AS b ON f.tourId = b.bookingsTourId
    GROUP BY tourGuideId) AS b
ON f.tourGuideId = b.tourGGuideId
ORDER BY tourId DESC
LIMIT 1