我有一个限制表,其中存储着coupon_id
,restriction_value
和restriction_type
。
coupon_id restriction_value restriction_type
-----------------------------------------
1 delhi city
2 delhi city
1 india country
我想返回一个查询,该查询为我提供适用于印度国家和德里城市的优惠券。
答案 0 :(得分:0)
分别查询每个条件,并验证是否存在相同的优惠券ID:
SELECT DISTINCT a.coupon_id
FROM tableA a
JOIN (SELECT coupon_id FROM tableA WHERE restriction_value = 'delhi' AND restriction_type = 'city') b ON b.coupon_id = a.coupon_id
JOIN (SELECT coupon_id FROM tableA WHERE restriction_value = 'india' AND restriction_type = 'country') c ON c.coupon_id = a.coupon_id
WHERE b.coupon_id = c.coupon_id
答案 1 :(得分:0)
选择城市“ delhi”的优惠券,该城市存在带有国家“印度”的记录。
像这样:
SELECT city.*
FROM my_table city
WHERE city.restriction_type = 'city'
AND city.restriction_value = 'delhi'
AND EXISTS (SELECT *
FROM my_table country
WHERE city.coupon_id = country.coupon_id
AND country.restriction_type = 'country'
AND country.restriction_value = 'india');
答案 2 :(得分:-1)
您可以编写如下的子查询。
SELECT
*
FROM coupon_table
where id in (
select coupon_id
from restriction_table
where (restriction_value = 'Delhi' AND restriction_type = 'city')
OR (restriction_value = 'India' AND restriction_type = 'country')
);