SELECT j.departure, stopDepartures.*
FROM journey j
JOIN journey_day ON journey_day.journey = j.id
JOIN service ON service.id = j.service
JOIN pattern ON j.pattern = pattern.id
JOIN (
SELECT section, pl.from_stop
FROM pattern_link pl
WHERE pl.section = section
) stopDepartures ON stopDepartures.section = pattern.section
WHERE service.id = "59924-44-X4-B-y10-2" AND journey_day.day = 1 AND pattern.direction = "outbound" AND DATE(NOW()) BETWEEN service.date_start AND service.date_end
GROUP BY j.id
ORDER BY departure ASC;
目前,上述查询的结果如下所示:
`departure` | `section` | `from_stop`
07:00 some_var_id some_var_id
但是
stopDepartures
联接实际上为每个from_stop
返回许多section
字段,但是我只会看到第一个。如何更改stopDepartures
连接,使其像数据透视表一样工作,并将每个from_stop
作为列返回? (很多列,而不是每个第一个from_stop
值1列) 最佳答案
如果我正确理解,这可能会做您想要的。代替:
SELECT j.departure, stopDepartures.*
做:
SELECT j.departure, group_concat(from_stop)
这会将所有值放入以逗号分隔的列表中。这不是每个单独的列,但是它可以满足您的需求。
关于mysql - 子查询选择行作为列(数据透视),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25947661/