Reputation: 9324
I'm a bit new to JOIN
and I'm finding it difficult to understand how I can query one table with ORDER BY
and LIMIT
and using only ORDER BY
on my JOINED
'right' table I think it is? So Basically if I was to query the two tables individually I would use these queries:
SELECT * FROM posts ORDER BY dateSubmitted DESC LIMIT ?,5
'?' standing for my bind_param()
because I'm creating a pagination. Now for my 'right' Second table:
SELECT * FROM postcomments WHERE postcomments.postID = posts.ID ORDER BY dateSubmitted DESC
As far as my understanding goes to 'link' the two tables together I want to be using LEFT JOIN
so that I will receive all my data from the 'left' table (being posts).
SELECT * FROM posts LEFT JOIN postcomments ON postcomments.postID = posts.ID
Now I can do this but I'm unsure where I would but my ORDER BY
and LIMIT
for both tables?
I've seen several different ways and I think this is what's getting me confused like I've seen this:
SELECT p.* FROM posts p ORDER BY posts.dateSubmitted DESC LIMIT ?,5
LEFT JOIN (SELECT * FROM postcomments
WHERE postscomments.postID = p.ID ORDER BY postcomments.dateSubmitted);
But I'm really unsure how to structure my query :S Any help appreciated :)
Upvotes: 2
Views: 7791
Reputation: 13465
It will be at the end like this:
Select * from
(SELECT * FROM posts ORDER BY dateSubmitted DESC LIMIT ?,5) as tempPost
LEFT JOIN postcomments on (postscomments.postID = tempPost.ID)
Upvotes: 3