您必须在表上使用自联接才能获得结果。
select t1.id
from yourtable t1
inner join yourtable t2
on t1.id = t2.col1
where
(
t1.col2 = 'vitaminA' and t1.col3 = 'vitaminB'
or t1.col2 = 'vitaminB' and t1.col3 = 'vitaminA'
)
and t2.col2 = 'price'
and cast(t2.col3 as int) < '30';
请参阅带有演示的 SQL Fiddle
或者您可以使用一个WHERE
子句EXISTS
:
select t1.id
from yourtable t1
where
(
t1.col2 = 'vitaminA' and t1.col3 = 'vitaminB'
or t1.col2 = 'vitaminB' and t1.col3 = 'vitaminA'
)
and exists (select t2.col1
from yourtable t2
where t2.col2 = 'price'
and cast(t2.col3 as int) < 30
and t1.id = t2.col1)
请参阅带有演示的 SQL Fiddle
附带说明一下,您当前的数据结构很难使用。如果可能,您可能需要考虑重组您的表格。