Одним из вариантов является использование динамического SQL для создания запроса с несколькими операторами пересечения.
Или просто используйте JOIN
для VariantValues с OptionValue.Затем используйте GROUP BY
+ HAVING
, чтобы сделать все значения OptionValue равными
; with
-- generate sample table tbl_VariantValues
tbl_VariantValues as
(
select productID = 399, variantID = 11, optionID = 16, valueID = 1 union all
select productID = 399, variantID = 12, optionID = 16, valueID = 1 union all
select productID = 399, variantID = 13, optionID = 16, valueID = 1 union all
select productID = 399, variantID = 14, optionID = 16, valueID = 1 union all
select productID = 399, variantID = 15, optionID = 16, valueID = 1 union all
select productID = 399, variantID = 13, optionID = 17, valueID = 4 union all
select productID = 399, variantID = 14, optionID = 17, valueID = 4 union all
select productID = 399, variantID = 19, optionID = 17, valueID = 4 union all
select productID = 399, variantID = 13, optionID = 18, valueID = 5 union all
select productID = 399, variantID = 15, optionID = 18, valueID = 5 union all
select productID = 399, variantID = 19, optionID = 18, valueID = 5
),
-- your OptionValue sample
OptionValueList as
(
select productID = 399, optionID = 16, valueID = 1 union all
select productID = 399, optionID = 17, valueID = 4 union all
select productID = 399, optionID = 18, valueID = 5
)
-- the query
select v.variantID
from tbl_VariantValues v
inner join OptionValueList o on v.productID = o.productID
and v.optionID = o.optionID
and v.valueID = o.valueID
group by v.variantID
having count(*) = (select count(*) from OptionValueList )
.