0

我想将一列的值与几个列表进行比较,并在每种情况下打印其他内容。它的汽车品牌列表,如雪佛兰、福特等。我的逻辑应该是这样的:

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

mycolumn 的值 like Chevy-1234,所以它必须是 like ,因为数字会改变。我怎么能在 MySQL 中做到这一点?

谢谢!

4

3 回答 3

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
于 2013-03-06T11:39:48.110 回答
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)
于 2013-03-06T12:57:48.113 回答
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
于 2013-03-06T12:00:02.073 回答