开发者

Mysql WHERE optional

开发者 https://www.devze.com 2023-02-25 11:49 出处:网络
if i have an example table like id || value_a I want to select 5 entries where value_a = 1. Quite simple so far, but now if there are less results than 5, i want to still have 5 results. So if the

if i have an example table like

id || value_a

I want to select 5 entries where value_a = 1. Quite simple so far, but now if there are less results than 5, i want to still have 5 results. So if there are 3 entries with value_a = 1, then I want to get those 3 results and 2 o开发者_StackOverflowther ones where value_a can be anything. How can i achieve this in the best way?


You can order by the result of a comparison calculation, like so:

SELECT stuff FROM table ORDER BY (value_a = 'value you want') DESC LIMIT 5


(
SELECT  *
FROM    mytable
WHERE   value_a = 1
LIMIT 5
)
UNION ALL
(
SELECT  *
FROM    mytable
WHERE   value_a <> 1
LIMIT 5
)
ORDER BY
        value_a = 1 DESC
LIMIT 5

This will use an index on value_a efficiently

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号