Search code examples
mysqldatabaselimit

How to limit the number of results of this MySQL query


I have a table questions, with columns question_id, question_title and question_topic(c or java). How do I write a query that returns all 'c' questions?

If however, the number of 'c' questions is less than say 5, I also include 'java' questions, so that the total number of results is at most 10.


Solution

  • try this:

    select * from questions where question_topic = 'c'
    union
    select * from questions where question_topic in ("c","java") order by question_type limit 10;
    

    the first select gives you all the C questions and the second gives you the first 10. When you union you don't get duplicates