简体   繁体   English

有having子句如何在组中使用或调节

[英]How to use or condition in group by having clause

How we can use OR condition in group by clause below is my sql query 我们如何在下面的group by子句中使用OR条件是我的SQL查询

SELECT count(id) as num_rows, 
        (3959 * acos ( cos ( radians(41.766908)) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-81.1526976)) + sin ( radians(41.766908) ) * sin( radians( lat ) ))) AS distance
FROM (`items`) 
WHERE `status` = 1 
GROUP BY `distance` 
HAVING `distance` <=50

In this query I have to add OR condition as well with group by clause that is 在此查询中,我还必须使用group by子句添加OR条件,即

 (GROUP BY `distance` HAVING `distance` <=50 OR `nationwide`=1)

How we can execute above query ?? 我们如何执行上面的查询?

Below is my result - and I have to add OR condition in having by clause 以下是我的结果-我必须在具有by子句的情况下添加OR条件

id nationwide distance id全国距离

1 2 22.4347083649522 1 2 22.4347083649522

1 2 46.8127635462102 1 2 46.8127635462102

8 2 10.0201103523007 8 2 10.0201103523007

13 1 11.888890536392 13 1 11.888890536392

GROUP BY `distance`, `nationwide`
HAVING `distance` <= 50 OR `nationwide` = 1
;

Note this will GROUP the COUNT s by both field values; 注意,这将通过两个字段值对COUNT if you want the count of all where nationwide = 1 and the count of all where distance >= 50 separately, you will need two separate queries... and a UNION really wouldn't make sense, since distance will be irrelevant in the first, and nationwide irrelevant in the latter. 如果要分别计算全国= 1的所有点数和距离> = 50的所有点数,则需要两个单独的查询... UNION真的没有意义,因为距离在第一个中是无关紧要的,与后者无关。

Just use a comma (,) 只需使用逗号(,)

(GROUP BY distance HAVING distance <=50, nationwide =1) (按distance分组的distance <= 50, nationwide = 1)

可能会对您有帮助

GROUP BY `distance`(HAVING `distance` <= 50 OR `nationwide` = 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM