2011-07-19 95 views
2

有兩個表,第一個包含基於類別的第一個數據和第二個元數據。基於數據中列的條件

table1 
id, category1, category2, custom1, custom2, custom3... 

table2 
category1, category2, denom, field 

實施例:

table1 
AAAAA, Car, Compact, Red, Automatic, 150bhp 

table2 
Car, Compact, Color, custom1 

在到表1中的字段,我們有用於元數據表2點的「字段」列。

現在我所要做的是以某種方式使用sql中'field'列的值作爲列。

select * from table1 
where table1.category1 = 'Car' 
    and table1.category2 = 'Compact' 
    and table1.category1 = table2.category1 
    and table1.category2 = table2.category2 
    and table2.denom = 'Color' 
    and table1.(value of table2.field) = 'Red' 

這是可能在一個單一的SQL語句?

回答

2

如果您事先知道「自定義」列的數量,則可能是這樣。

可以更換

and table1.(value of table2.field) = 'Red' 

and case table2.field 
     when 'custom1' then table1.custom1 
     when 'custom2' then table1.custom2 
     when 'custom3' then table1.custom2 
     ... 
     else NULL 
     end 
     = 'Red' 
+0

謝謝您的回答,希望對一些地方的列並沒有被列爲這使得你必須編輯查詢,如果列將在未來添加。但這應該工作:) – Mikael