在一行中连接多个相同列的查询

时间:2017-09-13 09:25:49

标签: php mysql laravel loops foreach

我想做这个 image 1

这是我的查询

SELECT 
    modules.nama_module,
    seats.from_seat,
    seats.until_seat,
    seats.available,
    seats.id_seat
FROM `modules`
RIGHT JOIN `seats` ON modules.id_module = seats.id_module
WHERE seats.id_day=1 OR seats.id_day=2

我应该怎样做才能做到这一点?

image output

2 个答案:

答案 0 :(得分:1)

试试这个。请注意,我创建了两列,一列列出了逗号分隔的seat_ids,另一列列出了座位数。您只需要创建您在屏幕截图上显示的视图所需的座位数,但我保留seat_ids以使输出与您的建议类似:

SELECT 
    modules.nama_module,
    seats.from_seat,
    seats.until_seat,
    seats.available,
    GROUP_CONCAT(seats.id_seat) as seat_ids,
    COUNT(seats.id_seats) as seats_count
FROM `modules`
RIGHT JOIN `seats` ON modules.id_module = seats.id_module
WHERE seats.id_day=1 OR seats.id_day=2
GROUP BY modules.nama_module, seats.from_seat, seats.until_seat

为每个新的seat_id创建新列有其自身的问题。创建列名,尴尬查询等。

[编辑:]刚刚将nama_module列添加到GROUP BY,因为我意识到不同服务的时间可能重叠(我是对的吗?)

答案 1 :(得分:-1)

您的查询中缺少分组依据和总和

SELECT 
    modules.nama_module,
    seats.from_seat,
    seats.until_seat,
    seats.available,
    seats.id_seat,
    sum(seats.id_seat) as nb_seat_available
FROM `modules`
RIGHT JOIN `seats` ON modules.id_module = seats.id_module
WHERE seats.id_day=1 OR seats.id_day=2
GROUP BY seats.from_seat