在fieldname中变换var @var

时间:2013-01-30 12:26:13

标签: mysql sql

在此查询中:

set @myVars := '';
SELECT C.Id,
      IF((select count(CA.Id) from mytable_2 CA where CA.IdC=C.Id and CA.IdA=10), 
      @myVars:='option_1' , 
      @myVars:='option_2')  as myTempField
FROM mytable_1 C where CONCAT('fied_',@myVars) = 5

在这种情况下,我希望' CONCAT('fied _',@ myVars)'成为我要查询的字段的名称,但它不起作用。< / p>

根据'if'的结果,将被质疑的字段必须是'field_option_1'或'field_option_2'

我怎么做?

1 个答案:

答案 0 :(得分:0)

您可以添加额外的列

set @myVars := '';
SELECT
  C.Id,
  IF((select count(CA.Id) from mytable_2 CA where CA.IdC=C.Id and CA.IdA=10), @myVars:='option_1', @myVars:='option_2') as myTempField,
  CONCAT('fied_',@myVars) as AColumn
FROM mytable_1 C
where @myVars = 5

这将为您提供id,myTempField和AColumn