(SQL) 为结点中的每个 ID 获取一列 table
(SQL) Getting a column for every ID out of a junction table
[如果这个问题已经在其他地方得到了回答,我会感激地接受 link 并删除它]
我有一个播放列表table:
pid | name
1 | playlist 1
2 | playlist 2
3 | playlist 3
还有一首歌table:
sid | name
1 | song 1
2 | song 2
3 | song 3
他们与这个路口有联系table:
pid | sid
1 | 1
1 | 2
1 | 3
2 | 2
3 | 1
我已经设法让连接开始工作
SELECT playlists.pid, songs.*
FROM playlists
INNER JOIN playlist_contains_song
ON playlists.pid = playlist_contains_song.pid
INNER JOIN songs
ON playlist_contains_song.sid = songs.sid;
这给了我这个结果:
pid | sid | name
1 | 1 | song 1
1 | 2 | song 2
1 | 3 | song 3
2 | 2 | song 2
3 | 1 | song 1
现在我想知道是否有办法获取这些数据'horizontally'。
首选输出应如下所示:
pid | 1 | 2 | 3
1 | 1 | 1 | 1
2 | 0 | 1 | 0
3 | 1 | 0 | 0
列是 sid,值代表 true 或 false,表示歌曲是否在播放列表中。
提前致谢!
使用数据透视查询:
SELECT pid,
COUNT(*) FILTER (WHERE sid = 1) AS "1",
COUNT(*) FILTER (WHERE sid = 2) AS "2",
COUNT(*) FILTER (WHERE sid = 3) AS "3"
FROM playlist_contains_song
GROUP BY pid
ORDER BY pid;
[如果这个问题已经在其他地方得到了回答,我会感激地接受 link 并删除它]
我有一个播放列表table:
pid | name
1 | playlist 1
2 | playlist 2
3 | playlist 3
还有一首歌table:
sid | name
1 | song 1
2 | song 2
3 | song 3
他们与这个路口有联系table:
pid | sid
1 | 1
1 | 2
1 | 3
2 | 2
3 | 1
我已经设法让连接开始工作
SELECT playlists.pid, songs.*
FROM playlists
INNER JOIN playlist_contains_song
ON playlists.pid = playlist_contains_song.pid
INNER JOIN songs
ON playlist_contains_song.sid = songs.sid;
这给了我这个结果:
pid | sid | name
1 | 1 | song 1
1 | 2 | song 2
1 | 3 | song 3
2 | 2 | song 2
3 | 1 | song 1
现在我想知道是否有办法获取这些数据'horizontally'。 首选输出应如下所示:
pid | 1 | 2 | 3
1 | 1 | 1 | 1
2 | 0 | 1 | 0
3 | 1 | 0 | 0
列是 sid,值代表 true 或 false,表示歌曲是否在播放列表中。
提前致谢!
使用数据透视查询:
SELECT pid,
COUNT(*) FILTER (WHERE sid = 1) AS "1",
COUNT(*) FILTER (WHERE sid = 2) AS "2",
COUNT(*) FILTER (WHERE sid = 3) AS "3"
FROM playlist_contains_song
GROUP BY pid
ORDER BY pid;