如何选择条件存储在表中的mysql行?

时间:2016-06-19 23:21:33

标签: mysql sql

我有一个存储用户搜索状态的表。它看起来像这样:

id | user_id | option | condition | value
------------------------------------------
 4 |       2 | price  | >=        | 300000
 5 |       2 | price  | <=        | 900000
 6 |       4 | status | =         | 1     
 7 |       4 | type   | =         | 1     
 8 |       5 | price  | >=        | 100000
 9 |       5 | price  | <=        | 125000
10 |       5 | status | =         | 2     
11 |       5 | type   | >=        | 2     
13 |       6 | price  | >=        | 200000
14 |       7 | price  | >=        | 500000
18 |       8 | price  | <=        | 600000
------------------------------------------

现在,我需要让所有user_id price 400000status适合任何条件范围(每个用户),或1匹配2,4,6,8

因此,对于此查询,结果应为{{1}}。

欢迎任何建议!

UPD:http://sqlfiddle.com/#!9/ea73a4/1

1 个答案:

答案 0 :(得分:0)

尝试以下内容;)

select distinct s.`user_id`
from `search_state` s
inner join (
    select `option`, `user_id`, max(`value` + 0) as maxV, min(`value` + 0) as minV, group_concat(`condition`) as `condition`
    from `search_state` 
    where `user_id` = `user_id`
    and `option` = `option`
    and `option` = 'price'
    group by `option`, `user_id`
) t on s.`option` = 'status' and s.`value` = '1'
or (
    s.`option` = 'price' and (
        s.`user_id` = t.`user_id`
        and s.`option` = t.`option` and
        case 
            when t.maxV = t.minV and find_in_set(',', t.`condition`) <> 0
                then 400000 = t.`maxV`
            when t.maxV = t.minV and find_in_set(',', t.`condition`) = 0 and t.`condition` = '>='
                then 400000 >= t.maxV
            when t.maxV = t.minV and find_in_set(',', t.`condition`) = 0 and t.`condition` = '<='
                then 400000 <= t.maxV
            when t.maxV <> t.minV then (400000 >= t.minV and 400000 <= t.maxV)
         end
    )
)

SQLFiddle DEMO HERE