Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...