PHP - 内部联接表具有相同Id的行

时间:2018-04-20 15:31:10

标签: php mysql

我想将一张表加入其他

表1:歌曲

@ApiParam(name = "sort", value = "Sort", type = "string")

表2:文件

╔════╦═══════╦════════╗
║ Id ║ Title ║ Artist ║
╠════╬═══════╬════════╣
║ 10 ║ abc   ║ acc    ║
║ 11 ║ dfg   ║ rtty   ║
╚════╩═══════╩════════╝

(song_id - “来自table1”

我想在表内联显示它们:

╔════╦══════════╦═════════╦═════════╗
║ id ║ filename ║ Version ║ song_id ║
╠════╬══════════╬═════════╬═════════╣
║  1 ║ 125.mp3  ║ version1║      10 ║
║  2 ║ 45.mp3   ║ version2║      10 ║
╚════╩══════════╩═════════╩═════════╝

我试过这个

╔═══════╦════════╦══════════╦══════════╗
║ Title ║ Artist ║ version1 ║ version2 ║
╠═══════╬════════╬══════════╬══════════╣
║ abc   ║ acc    ║ 125.mp3  ║  45.mp3  ║
╚═══════╩════════╩══════════╩══════════╝

获取后我尝试将它们放入数组中 喜欢这个

 SELECT * FROM songs 
    INNER JOIN files on 
    files.song_id = songs.id

但它给了我行foreach文件不在同一行!我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT *,
  (SELECT filename FROM files f WHERE f.song_id = s.id AND f.version = 'version1') AS version1,
  (SELECT filename FROM files f WHERE f.song_id = s.id AND f.version = 'version2') AS version2

FROM songs s

WHERE s.id = 10

您可以在线查看结果: http://sqlfiddle.com/#!9/a41db3/14

╔════╦═══════╦════════╦══════════╦══════════╗
║ id ║ title ║ artist ║ version1 ║ version2 ║
╠════╬═══════╬════════╬══════════╬══════════╣
║ 10 ║ abc   ║ acc    ║ 125.mp3  ║ 45.mp3   ║
╚════╩═══════╩════════╩══════════╩══════════╝

答案 1 :(得分:0)

看起来你需要两次加入files表,一次用于 Clean 版本,一次用于 Dirty - 以及之后每次都是同一张桌子,你需要别名。试试这个:

SELECT * 

FROM songs

INNER JOIN files AS cf
    ON cf.song_id = songs.song_id
    AND cf.version = 'Clean'

INNER JOIN files AS df
    ON cf.song_id = songs.song_id
    AND cf.version = 'Dirty'