我正在尝试将几张表合并成一行。
队桌:
+----+-------+
| id | team |
+----+-------+
| 10 | Team1 |
| 11 | Team2 |
| 12 | Team3 |
+----+-------+
位置表:
+----+-----------+
| id | location |
+----+-----------+
| 1 | location1 |
| 2 | location2 |
| 3 | location3 |
+----+-----------+
停止表:
+----+---------+-------------+---------------------+
| id | team_id | location_id | timestamp |
+----+---------+-------------+---------------------+
| 1 | 10 | 2 | 2019-11-07 15:27:42 |
| 2 | 10 | 3 | 2019-11-07 16:37:52 |
| 3 | 10 | 4 | 2019-11-07 17:47:62 |
+----+---------+-------------+---------------------+
希望创建所需的表:
+----+---------+---------------------+---------------------+---------------------+
| id | team_id | (loc id=2) | (loc id=3) | (loc id=4) |
+----+---------+---------------------+---------------------+---------------------+
| 1 | 10 | 2019-11-07 15:27:42 | 2019-11-07 16:37:52 | 2019-11-07 17:47:62 |
| 2 | 11 | | | |
| 3 | 12 | | | |
+----+---------+---------------------+---------------------+---------------------+
总是会有数量有限的位置。
任何指导将不胜感激!我已经尝试了一些LEFT JOINS,但距离还很远。
答案 0 :(得分:1)
您可以进行条件聚合:
select
t.id team_id
max(case when s.location_id = 2 then timestamp end) loc_id_2,
max(case when s.location_id = 3 then timestamp end) loc_id_3,
max(case when s.location_id = 4 then timestamp end) loc_id_4
from
team t
left join stops s on s.team_id = t.id
group by t.id
如果您想为生成的结果动态生成一个id
列(这几乎没有意义,因为您已经为每个team_id
获得了一条记录),则可以使用row_number()
(在MySQL 8.0及更高版本中可用):
select
row_number() over(order by t.id) id,
t.*
from (
select
t.id team_id,
max(case when s.location_id = 2 then timestamp end) loc_id_2,
max(case when s.location_id = 3 then timestamp end) loc_id_3,
max(case when s.location_id = 4 then timestamp end) loc_id_4
from
team t
left join stops s on s.team_id = t.id
group by t.id
) t