Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

mysql - How to LEFT JOIN three tables with the same column name

I have a three tables that are left join. two of them have uid as user id. Problem is every time query execute it takes the same user id.

Please check the table structure

-------------------------------------
|Users      |posts      |favorites  |
|-----------|-----------|-----------|
|user_id    |id         |id         |
|username   |title      |uid        |
|password   |post       |post_id    |
|           |uid        |           |
|           |favorites  |           |
-------------------------------------

MySQL query

SELECT * FROM favorites 
LEFT JOIN users ON users.user_id = favorites.uid 
LEFT JOIN posts ON favorites.posts_id = posts.id
WHERE favorites.uid='$id' and posts.active=1

please note that $id is the profile owner (user) id. Any help will be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If the table was as follows (I've renamed user_id, post, and favorites columns to clarify their roles as I understand them)

-------------------------------------
|Users      |posts      |favorites  |
|-----------|-----------|-----------|
|id         |id         |id         |
|username   |title      |uid        |
|password   |post_text  |post_id    |
|           |uid        |           |
|           |fav_id     |           |
-------------------------------------

This sql code can be used to get what (I think) you want

SELECT * FROM favorites 
LEFT JOIN posts ON  favorites.id = posts.fav_id
LEFT JOIN users ON posts.uid = users.id
WHERE favorites.uid='$id' and posts.active=1

This should get all the details of favorite posts from the three tables for the given user id. Hope it works for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...