There are two tables, the first contain data and the second meta data for the first based on category.
table1
id, category1, category2, custom1, custom2, custom3...
table2
category1, category2, de开发者_如何学Pythonnom, field
Example:
table1
AAAAA, Car, Compact, Red, Automatic, 150bhp
table2
Car, Compact, Color, custom1
The 'field' column in table2 points to which field in table1 we have meta data for.
Now what I am looking to do is to somehow use the value of the 'field' column in an sql as the column.
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'
Is this possible to do in a single sql statement?
It is possible if you know the number of "custom" columns in advance.
you can replace
and table1.(value of table2.field) = 'Red'
with
and case table2.field
when 'custom1' then table1.custom1
when 'custom2' then table1.custom2
when 'custom3' then table1.custom2
...
else NULL
end
= 'Red'
精彩评论