开发者

Mysql - Joining on multiple IDs and concating joined column?

Not sure how accurate my question title is but let me explain a little better.

I have two tables: artists, releases

table artist
  artist_id, 
  artist_name

table release
  release_id,
  release_art开发者_Python百科ist_ids,
  release_name

There are more column names, but these are the ones involved in my problem.

release_artist_ids can contain one or more artist IDs that correspond to the artist table. If more than one artist features on the same release_id then I had comma separated the IDs.

So an example release row:

1 -- 2,5 -- Example Release

What I would like to do is list the releases and join the artist table to fetch the artist names involved in the release.

I managed to join using IN (release.release_artist_ids) but this only brings back one artist name. I would like to merge all involved artists into one returned column, separated by a pipe so I can format later on.


I suggest that you change your database design to have a join table called release_artist that models the many-to-many relationship between artists and releases. This table should have two columns: release_id and artist_id.

If you can't change the database design, you can use FIND_IN_SET but it will be slow:

SELECT
   release.release_id,
   GROUP_CONCAT(artist.artist_name, '|') AS artist_names
FROM artist 
JOIN release
ON FIND_IN_SET(artist.id, release.release_artist_ids)
GROUP BY release.release_id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜