How can I fetch two sets of results in a single MySQL query from the same table?
As the other answer says - you can combine results using union
- which simply means to join two results together. What is important to note, however, is that you can't simply union
those two queries together directly, as they use order by
, so we need to wrap them in outer queries, and use a ranking variable to ensure we can reconstruct the union in the order that we want:
select * from (
SELECT 1 as tbl,
comments.userid,
users.username,
comments.comment,
comments.ratings,
comments.datetime,
comments.record_num,
content.uploader,
content.anonymous,
@rank := @rank + 1 as rank
FROM comments
LEFT JOIN users ON comments.userid = users.record_num
LEFT JOIN content ON comments.content = content.record_num
CROSS JOIN (select @rank := 0 ) q
WHERE comments.content = ? ORDER BY comments.ratings DESC limit 3
) q1
UNION ALL
select * from (
SELECT 2 as tbl,
comments.userid,
users.username,
comments.comment,
comments.ratings,
comments.datetime,
comments.record_num,
content.uploader,
content.anonymous,
@rank := @rank + 1 as rank
FROM comments
LEFT JOIN users ON comments.userid = users.record_num
LEFT JOIN content ON comments.content = content.record_num
CROSS JOIN (select @rank := 0 ) q
WHERE comments.content = ? ORDER BY comments.datetime DESC limit ?, ?
) q2
ORDER BY tbl asc, rank asc;
union
by default is distinct
meaning that it won't duplicate rows found in both result sets, however there is also no guarantee that the rows will be returned in the order you expect, hence the need to mark each table with its own tbl
value, and then order by
that field.
If you were certain there would be no duplicates, you could eliminate the duplicate check by using union all
, instead of union