Double rule in LIMIT

Asked

Viewed 99 times

7

I have a news table with the fields titulo, conteudo and destaque, being the highlight int(1), is a boolean value just to check whether a news is featured or not, what I would like to do is select a amount of news and within that amount X news need to be highlights (destaque=1), something like that:

SELECT * FROM noticias WHERE destaque = 1 limit 5 AND ... LIMIT 30.

That is, 30 news, 5 of them highlights and the rest (25) "common".

How can I do that?

1 answer

7


Take the 5 that need a criterion, that is, that they are highlighted, and then take the other 25 that do not need this criterion.

SELECT * FROM noticias WHERE destaque = 1 limit 5
UNION ALL
SELECT * FROM noticias WHERE destaque <> 1 limit 25

I put in the Github for future reference.

I doubt that this is a consultation that produces an interesting result, but it meets the criteria set out in the question.

  • 2

    I would still put UNION ALL since all results will be guaranteed to be different

  • @Jeffersonquesado see some advantage? Does it optimize?

  • About "... Query produce an interesting result", are there better solutions? make each query separate?

  • 1

    I don’t know, only you know what you want, but is likely to exist, after all to take things loose so from the database will hardly be something useful and probably will always come the same things (except probably the highlights if they are being exchanged over time, but the other news will never change, so it won’t be exactly news)

  • I understood, but I would put to filter by ID

  • That’s not in your question.

  • But it wouldn’t just put the ORDER BY id ASC/DESC at the end of the instruction?

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.