MySQL使用`IN`同时具有多个值

时间:2014-09-09 14:53:36

标签: mysql sql

我正在尝试从20英里范围内的商店列表中计算每家商店出售的优惠券。我知道如果只有一个商店,以下语法将起作用。

SELECT sum(couponscount)作为计数restaurant IN(SELECT storename其中bhal bhal bhal和输出是一个值)

IN (SELECT商店名where bhal bhal bhal and output is multiple values)会返回多个值?

就像我的情况一样,完整的SQL就像它不起作用

SELECT sum(couponscount) as count FROM `coupons` having `restaurant` IN (SELECT `storename`, ((ACOS(SIN(-27.561264299999998 * PI()/180) * SIN(latitude * PI()/180) + COS(-27.561264299999998 * PI()/180) * COS(latitude * PI()/180) * COS((153.07304890000003 – longitude) * PI()/180)) *180 / PI( )) *60 * 1.1515) AS `distance` FROM `stores` WHERE `status`=’active’ HAVING `distance` <=20)

有没有让它运作?

2 个答案:

答案 0 :(得分:1)

据推测,您希望在距离为20的商店中获取优惠券的数量。将having条件移至where条款应该可以达到您想要的效果:

SELECT sum(couponscount) as count
FROM `coupons`
WHERE `restaurant` IN (SELECT `storename`
                       FROM `stores`
                       WHERE `status` = 'active' AND
                              ((ACOS(SIN(-27.561264299999998 * PI()/180) * SIN(latitude * PI()/180) + COS(-27.561264299999998 * PI()/180) * COS(latitude * PI()/180) * COS((153.07304890000003 – longitude) * PI()/180)) *180 / PI( )) *60 * 1.1515) <= 20
                      );

您遇到了一个主要的语法问题,因为您的子查询返回了两列。当您使用带有in的子查询时,您只能返回一列,在本例中为storename。我将距离计算的代码移动到where子句。子查询或外部查询中不需要having子句。

答案 1 :(得分:1)

SELECT sum(couponscount) AS COUNT,restaurant
FROM `coupons`
WHERE `restaurant` IN
    (SELECT `storename`
     FROM `stores`
     WHERE `status`='active'           
       AND
      ((ACOS(SIN(-27.561264299999998 * PI()/180) * SIN(latitude * PI()/180) + COS(-27.561264299999998 * PI()/180) * COS(latitude * PI()/180) * COS((153.07304890000003 – longitude) * PI()/180)) *180 / PI()) *60 * 1.1515) <=20)
GROUP BY restaurant

也可以使用适当的引号进行激活。