2017-04-04 50 views
0

我有2个表:pf_rowsMySQL的选择与IF或CASE和子查询

| g1 | g2 | g3 | g4 | 
+------+------+------+------+ 
| foo1 | foo2 | foo3 | foo4 | 
+------+------+------+------+ 

pf_seq

| lite | qty | 
+------+-----+ 
| 1 | 12 | 
+------+-----+ 
| 2 | 12 | 
+------+-----+ 

我需要一个查询从pf_rows基于价值的东西存在于pf_seq返回值。 我爱:当pf_seq.lite=1那么结果是foo1pf_seq.lite=2那么结果是foo2

回答

1

如果两个表都没有关系,你将不得不使用一个cross join

select t2.lite, 
     case 
      when t2.lite = 1 then t1.g1 
      when t2.lite = 2 then t1.g2 
      /* other cases if needed */ 
      else null 
     end as gx 
from pf_rows t1 
cross join 
     pf_seq t2 

注意,这种查询如果表中包含大量行,则根本不执行任何操作。