A
A
alesto2011-05-02 20:39:40
MySQL
alesto, 2011-05-02 20:39:40

Help compose a mysql select query, details under the cut

There is a plate in it 3 fields
category_id, post_id, date
The first is the category id, the second is the post id. the third is the time of adding the entry. Is it possible to pull out for specific headings the record that was added the very first and 2 records that were added the most recent (if there are any) for specific headings? And if not just one, how many requests do you need to make it work as quickly as possible?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
X
xiWera, 2011-05-02
@xiWera

select * from (select * from tbl order by date limit 1) as foo union select * from tbl order by date desc limit 3

@
@mgyk, 2011-05-02
_

I can suggest an alternative. If there are a lot of posts, we will get a warning, although here it just doesn’t bother us. (GROUP CONCAT does not support LIMIT)
select GROUP_CONCAT(post_id ORDER BY date desc),category_id from tmp GROUP BY category_id;
select GROUP_CONCAT(post_id ORDER BY date),category_id from tmp GROUP BY category_id;
This way you can pull data for all categories at once WHERE category_id IN (1,2,3,4,5). It is easier to cut off the required amount of post_id in the script, and not in the SQL itself (well, or LOCATE, LEFT, etc.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question