I have one table for posts where I save the开发者_运维技巧 type of each post in one field. Lets say I have two types - "type1" and "type2". I need to retrieve latest x posts from that table where x/2 posts are from "type1" and the other half is from "type2". How is that possible using one mysql query?
Ok so, your table is like this:
post_text post_type post_date
--------- --------- ---------
Hello World 1 2011-06-21
Foo Bar 2 2011-06-22
Fizz Buzz 2 2011-06-23
lol hai 1 2011-06-24
And you want to retrieve some number (x) of posts where half of them will be of type 1 and the other half of type 2?
One possible solution is this:
(SELECT post_text
FROM mytable
WHERE post_type = 1
ORDER BY post_date DESC
LIMIT 1)
UNION
(SELECT post_text
FROM mytable
WHERE post_type = 2
ORDER BY post_date DESC
LIMIT 1);
Of course the limit quantity should be half the desired quantity X.
This returns:
post_text post_type post_date
--------- --------- ---------
lol hai 1 2011-06-24
Fizz Buzz 2 2011-06-23
精彩评论