简体   繁体   中英

SQL: Join Parent - Child tables

I'm building a simple review website application and need some help with SQL Query.

There are 3 tables (Topics, Comments, Users). I need a SQL query to select the data from all 3 tables.

The 'Topics' table is the parent and the 'Comments' table contains the child records (anywhere from zero to 100 records per parent.

The third table 'Users' contains the user information for all users.

Here are the fields for the 3 tables:

Topics (topicID, strTopic, userID)
Comments (commentID, topicID, strComment, userID)
Users (userID, userName)

I tried:

SELECT * 
FROM   Topics 
  Inner Join Comments ON Topics.topicID = Comments.topicID
  Inner Join Users ON Topics.userID = Users.userID

But this does not work correctly because there are multiple topics and the User info is not joined to the Comments table. Any help would be appreciated.

You should do left join with Comment to get Topics with no comments and also join Topic and Comment with Users to get related user information for both.

SELECT * 
FROM Topics t
INNER JOIN Users tu on tu.userID = t.userID
LEFT JOIN Comments c on c.topicID = t.topicID
LEFT JOIN User cu on cu.userID = c.userID

You need to join to the user table twice.

SELECT *
FROM Topics
 INNER JOIN Comments ON Topics.topicID = Comments.topicID
 INNER JOIN Users AS u1 ON Topics.userID = u1.userID
 INNER JOIN Users AS u2 ON Comments.userID = u2.userID

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