I have following tables:
users(id, name)
posts (id, text, userId)
comments (id, text, userId, postId)
I want to return a post, its owner name, its comments, and the owner of each comment. I can't get data for the owner of the comment. I wrote this:
SELECT posts.id, posts.text, users.id, users.name, comments.text AS commentText, commenters.id, commenters.name
FROM posts
JOIN users
ON posts.userId = users.id
LEFT JOIN comments
ON posts.id = comments.postId
开发者_StackOverflow社区 LEFT JOIN users AS commenters
ON comments.userId = users.id
WHERE posts.id = @postId
The problem with this query is that the commenters.id, and commenters.name columns are coming back blank. Any idea where I've gone wrong?
Hmm, break the query down.
OK, firstly a small correction
SELECT posts.id, posts.text, users.id, users.name, comments.text AS commentText, commenters.id, commenters.name
FROM posts
JOIN users
ON posts.userId = users.id
LEFT JOIN comments
ON posts.id = comments.postId
LEFT JOIN users AS commenters
ON comments.userId = commenters.id
(you had users.id, not commenters.id)
secondly, if that doesnt fix it, break the query parts down, to check that the select * from comments, and join users, to check the link to users works. Do the same for posts.. if that works.. let me know and we can look further as to where its going wrong
精彩评论