简体   繁体   中英

SQL Query JOIN with 4 tables

Who can help me?

I have 4 tables , , and .

Here is the strucutre:

  • id
  • title
  • description

  • id
  • username
  • password

  • id
  • user_id
  • avatar
  • location

  • id
  • post_id
  • user_id
  • parent
  • comment
  • posted

I have a query which i want to display comments on specific post.

This is what i written but avatar column it doesn't show any results. It seems i written it wrong on join or something.

SELECT comments.id as comment_id,
    comments.user_id as user_id,
    comments.post_id as post_id,
    comments.parent as parent,
    comments.comment as comment,
    comments.posted as posted,
    users_details.avatar as avatar,
    users.username as username
FROM `comments`
    LEFT JOIN users ON users.id = comments.user_id
    LEFT JOIN users_details ON users_details.user_id = users.id
    WHERE comments.post_id='60337'
ORDER BY posted ASC

Here is a screenshot of the table with results https://i.imgur.com/VQ8KwV1.png

I want to mention the avatar field it has a value for that user in users_details table so it should be displayed...

Thanks!

Two potential reasons I could tell causing this issue.

1. The users do not have an avatar.

Try: Select Avatar from Users_Details where User_Id in (2,9212) and make sure it returns some data.

2. The Primary/Foreign key being used for joining the tables is not matching

Run those queries below and ensure that they are returning the same users.

select * from users where id in (2,9212) 
select * from users_details where user_id in (2,2912) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM