2

Is possible to make query to get first 3 comments ORDER BY rating, and rest of comments by timestamp?

Im using simple query to get comments on my script, and i sort it by timestamp, here is example

mysql_query("SELECT * FROM comments WHERE content = '$id' AND approved='1' AND parent_id ='0' ORDER BY timestamp DESC"); 

by default all comments have 0 rating in database

3
  • 1
    Have you tried ORDER BY rating DESC LIMIT 3 and then taking the ids of those and throwing them into WHERE id NOT IN (1, 2, 3) ORDER BY timestamp DESC ? You would have to have two separate queries, but since you're doing this in PHP, that should be simple. Commented Jun 22, 2014 at 21:52
  • for this i need to call two query in database? any chance to make in in one line ? Commented Jun 22, 2014 at 21:53
  • You can if you build a stored routine and call it through PHP Commented Jun 22, 2014 at 22:11

1 Answer 1

3

The query below returns the top 3 rated comments as the first 3 rows, and the most recent comments excluding the top 3 for the rest.

SELECT t1.* 
FROM 
(
    SELECT t2.* FROM (
      SELECT c.* , my_order 1 FROM comments c
      WHERE content = '$id'
          AND approved = '1' 
          AND parent_id = '0'
      ORDER BY rating DESC LIMIT 3
    ) t2
    UNION
    SELECT c.* , my_order 2 FROM comments c
    WHERE content = '$id' 
        AND approved = '1' 
        AND parent_id = '0' 
        AND id NOT IN (
            SELECT id FROM comments
            WHERE content = '$id'
              AND approved = '1' 
              AND parent_id = '0'
            ORDER BY rating DESC LIMIT 3
        )
) t1
ORDER BY 
    my_order, 
    (CASE WHEN my_order = 1 THEN rating ELSE timestamp END)
Sign up to request clarification or add additional context in comments.

4 Comments

This is beautiful SQL. I love it.
Why do you use subqueries?
@DanFromGermany to order the results of UNION. see stackoverflow.com/questions/421049/…
@FuzzyTree ah.. I forgot about that limitation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.