2016-06-19 6 views
1

Ich habe eine Tabelle, die Zustände der Benutzersuche speichert. Es sieht wie folgt aus:Wie wähle ich MySQL-Zeilen aus, in denen die Bedingung in einer Tabelle gespeichert ist?

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 
------------------------------------------ 

Nun, ich brauche alle user_id wo price Wert von 400000 passt in jede Zustandsbereich zu erhalten (pro Benutzer), OR status1 Streichhölzer.

Also, für diese Abfrage sollte das Ergebnis 2,4,6,8 sein.

Alle Vorschläge sind willkommen!

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

+1

können Sie wollen das Tabellenschema ändern Spalten zu haben wie 'PRICE_MIN, price_max'. Für einseitige Bereiche können Sie sehr große positive und negative Grenzen setzen. – Thilo

+0

Danke für den Rat. Ja, es mag funktionieren, aber ich mache mir Sorgen wegen einer großen Anzahl von Optionen. Jetzt können etwa 20 Optionen gespeichert werden. Und sie können weiterwachsen. – WarGasm

+0

Post ein sqlfiddle – Strawberry

Antwort

0

Versuche folgende;)

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

Verwandte Themen