简体   繁体   中英

mysql add condition when limit less than

I creating relative system for my site. I need query, when result rows less than i setup - 1 condition added.

My example:

SELECT * FROM `animal` WHERE (`color_id`=1) LIMIT 4

When result rows less than 4, i adding condition

SELECT * FROM `animal` WHERE (`color_id`=1) OR (`breed_id`=1) LIMIT 4

and continue

SELECT * FROM `animal` WHERE (`color_id`=1) OR (`breed_id`=1) OR (`type_id`=1) LIMIT 4

How do that in 1 query? if it possible

Re-Running altered Queries in case of the result set is to small is not the job of MYSQL, but of your code executing the queries.

A really "dirty" approach would be to use Union to ensure the resultset is always big enough, and finally just limit it to 4 rows (assuming the table contains at least 4 entries):

SELECT * FROM (
    SELECT * FROM `animal` WHERE (`color_id`=1) LIMIT 4
    UNION
    SELECT * FROM `animal` WHERE (`color_id`=1) OR (`breed_id`=1) LIMIT 4
    UNION
    SELECT * FROM `animal` WHERE (`color_id`=1) OR (`breed_id`=1) OR (`type_id`=1) LIMIT 4
    UNION 
    SELECT * FROM `animal` LIMIT 0,4
) as temp LIMIT 0,4

Technically this would fetch 4 rows for every query, and only add them to the resultset if it does not already contain that row. From the final result (16 rows worstcase) the first 4 rows are taken. If none of the first 3 queries delivers a result, the first 4 animals existing in the database are returned.

I'd do this in my application code.

But just to see if it works, can you try this:

select *
from `animal`
where `color_id` = 1
    or (
        `breed_id` = 1
        and (
            select count(*)
            from `animal`
            where `color_id` = 1
            ) < 4
        )
    or (
        `type_id` = 1
        and (
            select count(*)
            from `animal`
            where `color_id` = 1
                or `breed_id` = 1
            ) < 4
        ) LIMIT 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM