2013-03-06 54 views
0

我想比較列的值和幾個列表,並在每種情況下打印其他內容。它是一個汽車品牌的名單,如雪佛蘭,福特等。我的邏輯應該是這樣的:MySQL:列表和類似?

if(mycolumn like carlist1, 'this', '') 
if(mycolumn like carlist2, 'that', '') 
if(mycolumn like carlist3, 'foobar', '') 

mycolumn有一個像Chevy-1234的值,所以它必須是一個喜歡,因爲這些數字會發生變化。我怎麼能在MySQL中做到這一點?

謝謝!

+0

發表您的表模式,一些樣本數據和期望的輸出,你試過了什麼。 – 2013-03-06 11:38:33

回答

1

最好的辦法是到汽車列表存儲爲一個表,與像數據:

Chevy 
Ford 

等。

然後,你可以做你想做什麼聯接:

select t.*, 
     max(case when cl.brand = 'Chevy' then 'this' end) as Chevy, 
     max(case when cl.brand = 'Ford' then 'this' end) as Ford, 
     . . . 
from t left outer join 
    carlist cl 
    on left(t.col, length(cl.brand)) = cl.brand 
group by t.id 

否則,您必須處理數:

select (case when left(col, locate('-', col) - 1) = carlist1 then 'this' end), 
     (case when left(col, locate('-', col) - 1) = carlist2 then 'that' end), 
     (case when left(col, locate('-', col) - 1) = carlist3 then 'foobar' end) 
1

嘗試在mysql的這樣

SELECT 
    if(mycolumn like 'carlist1%', 'this', '') as 'Blah1', 
    if(mycolumn like 'carlist1%', 'that', '') as 'Blah2', 
    if(mycolumn like 'carlist1%', 'foobar', '') as 'Blah3' 
FROM mytable 
0

您可以使用

SELECT 
    WHEN mycolumn LIKE 'carlist1%' THEN 'this' END AS Blah1, 
    WHEN mycolumn LIKE 'carlist1%' THEN 'that' END AS Blah2, 
    WHEN mycolumn LIKE 'carlist1%' THEN 'foobar' END AS Blah3 
FROM mytable