2

Table A:

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

Table B:

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

For now, Is there any sql statement that can show the output as below:

Output:

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

Thanks.

Rahul Tripathi
  • 152,732
  • 28
  • 233
  • 299
  • @RahulTripathi MySQL – user3789802 Nov 20 '15 at 03:51
  • TableA: what's like_books column type? – Nguyễn Hải Triều Nov 20 '15 at 03:54
  • You don't normally use a comma-separated list in a database field to join to another database field. Many values per field break the [first normal form](https://en.wikipedia.org/wiki/First_normal_form). Reasonable database designs usually replace it [with an additional table](http://www.databaseprimer.com/pages/relationship_1tox/). – 9000 Nov 20 '15 at 03:57
  • @NguyễnHảiTriều VARCHAR(30) – user3789802 Nov 20 '15 at 04:02
  • @sirsince1990 Oh...my question is duplicate... – user3789802 Nov 20 '15 at 04:02
  • @9000 As you said, what is the better way for this case? – user3789802 Nov 20 '15 at 04:04
  • @user3789802: follow the second link. In your case I'd have table `user(id, name)`, table `book(id, name)` and table `user_likes_book(user_id foreign key user(id), book_id foreign key book(id))`. This is a classic [M:N or many-to-many relationship pattern](http://en.tekstenuitleg.net/articles/software/database-design-tutorial/many-to-many.html) – 9000 Nov 20 '15 at 04:11
  • @9000 Roger that and thanks for your information. – user3789802 Nov 20 '15 at 04:14

1 Answers1

3

Try this:

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

Rahul Tripathi
  • 152,732
  • 28
  • 233
  • 299