Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法编写SQL查询_Sql - Fatal编程技术网

无法编写SQL查询

无法编写SQL查询,sql,Sql,我有一个存储优惠券id、限制值和限制类型的限制表 我想返回一个查询,该查询提供适用于印度国家和德里市的优惠券。您可以编写如下子查询 SELECT * FROM coupon_table where id in ( select coupon_id from restriction_table where (restriction_value = 'Delhi' AND restriction_type = 'city') OR (re

我有一个存储优惠券id、限制值和限制类型的限制表


我想返回一个查询,该查询提供适用于印度国家和德里市的优惠券。

您可以编写如下子查询

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')
);

分别查询每个条件,并验证是否存在相同的优惠券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

选择城市“德里”的优惠券,该城市有国家“印度”的记录。 大概是这样的:

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');

您好,欢迎来到Stack Overflow。请显示您的表DDL、示例数据、预期结果以及您尝试到的无效日期。没有这个,,我们无法真正帮助您。给定一张优惠券,请编写一个sql查询,给出以下结果:优惠券适用于印度国家和城市。优惠券是一个单独的表?如何通过限制表中的where条件。我正在更新我的答案。我在优惠券id 2中添加了一个示例表……这不是必需的因为第二条记录也有同样的数据来自德里市。您可以使其唯一,然后应用该条件。
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');