I have two tables.
‘users’ table:
id name book1 book2 book3
1 Brian name1 name2 name3
2 John name3 name1 name2
‘library’ table:
id book_names position
1 name1 2
2 name2 3
3 name3 1
What I want is:
The book1 in the ‘users’ table, to match with the id 1 in the ‘library’ table.
The book2 in the ‘users’ table, to match with the id 2 in the ‘library’ table.
The book3 in the ‘users’ table, to match with the id 3 in the ‘library’ table.
And all these in order by position from the ‘library’ table.
I have tried this:
SELECT
l*, u.book1, u.book2, u.book3,
FROM library AS l
LEFT JOIN users AS u
ON u.id = l.user_id
WHERE u.id = ?
ORDER BY p.position DESC
2
Answers
I highly recommend to change your DB structure, as everyone said in comments. Something like this:
Then you can easy manipulate with data you have:
First of all you have to learn about How to normalize the tables.
Next, you have to change the structure of your
users
table which should look like below.users
table:After creating, when you insert some data, it should look like below.
Here we are using
id
column fromlibrary
table instead of name of the books. So that you could write SQL query easily.Note: I am not speaking about the
foriegn key
concept, its a bit advance, as a beginner, you will find difficult to manupulate the data manually via phpmyadmin. You could relate both tables via setting aforiegn key
once you learn more about this.Coming back to the query, now you can write a query like below
You can skip the
order by
clause since all the books have been brought in a single row. If you have anymore query regarding this, pls comment below.