SQL:如何使用逗号值加入另一个表?

时间:2015-11-20 03:49:26

标签: mysql sql

A

id  username  like_books 
-----------------------
1   Peter     1,2,3
2   John      1,2

B

id  book_name  
-----------------------
1   Legend
2   StackOverFlow
3   Google

现在, 是否有任何sql语句可以显示如下输出:

输出:

id username    like_books
------------------------------------
1  Peter       Legend,StackOverFlow,Google
2  John        Legend,StackOverFlow

感谢。

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT  a.id,a.username,
        GROUP_CONCAT(b.book_name ORDER BY b.id) like_books
FROM    A a
INNER JOIN B b ON FIND_IN_SET(b.id, a.like_books) > 0
GROUP   BY a.id

<强> FIDDLE DEMO