简体   繁体   English

Rails Active Record Mysql查找查询HAVING子句

[英]Rails Active Record Mysql find query HAVING clause

Is there a way to use the HAVING clause in some other way without using group by. 有没有一种方法可以使用其他方式使用HAVING子句而无需使用group by。

I am using rails and following is a sample sccenario of the problem that i am facing. 我正在使用Rails,以下是我所面临的问题的示例场景。 In rails you can use the Model.find(:all,:select,conditions,:group) function to get data. 在rails中,您可以使用Model.find(:all,:select,conditions,:group)函数获取数据。 In this query i can specify a having clause in the :group param. 在此查询中,我可以在:group参数中指定一个having子句。 But what if i dont have a group by clause but want to have a having clause in the result set. 但是,如果我没有group by子句但想要在结果集中有一个hading子句怎么办。

Ex: Lets take a query 例如:让我们查询

select sum(x) as a,b,c from y where "some_conditions" group by b,c; 从y中选择sum(x)作为a,b,c,其中“ some_conditions”按b,c分组;

This query has a sum() aggregation on one of the fields. 此查询在一个字段上具有sum()聚合。 No if there is nothing to aggregate then my result should be an empty set. 否,如果没有要汇总的内容,那么我的结果应该是一个空集。 But mysql return a NULL row. 但是mysql返回一个NULL行。 So this problem can be solved by using 所以这个问题可以通过使用解决

select sum(x) as a,b from y where "some_conditions" group by b having a NOT NULL; 从y中选择sum(x)作为a,b,其中“ some_conditions”按b分组,且NOT为NULL;

but what happens in case i dont have a group by clause?? 但是如果我没有group by子句怎么办? a query like below 如下查询

select sum(x) as a,b from y where "some_conditions"; 在“ some_conditions”中从y中选择sum(x)作为a,b;

so how to specify that sum(x) should not be NULL? 所以如何指定sum(x)不应该为NULL?

Any solution that would return an empty set in this case instead of a NULL row will help and also that solution should be doable in rails. 在这种情况下将返回空集而不是NULL行的任何解决方案都将有所帮助,并且该解决方案也应在rails中可行。

We can use subqueries to get this condition working with sumthin like this 我们可以使用子查询来使这种条件与sumthin一起工作,如下所示

select * from ((select sum(x) as b FROM y where "some_condition") as subq) where subq.b is not null; 选择* from((将sum(x)选择为b FROM y,其中“ some_condition”作为subq),其中subq.b不为null;

but is there a better way to do this thru sql/rails ?? 但是通过sql / rails有没有更好的方法呢?

The sub query is the standard way to handle this situation in SQL. 子查询是在SQL中处理这种情况的标准方法。 However, I recommend that you don't use the sub query or HAVING, and instead check to see if SUM(x) is NULL. 但是,我建议您不要使用子查询或HAVING,而应检查SUM(x)是否为NULL。 It's best to always return a result so you don't have to check to see if you have one or not. 最好总是返回一个结果,这样就不必检查是否有结果。 If the value is NULL, then you know there were no records with NON NULL values. 如果该值为NULL,则您将知道没有带有NULL值的记录。

One thing you didn't mention, if you don't want sum(x) to be null then you can do this: 您没有提到的一件事,如果您不希望sum(x)为null,则可以执行以下操作:

SELECT IFNULL(SUM(x), 0) AS a FROM table

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

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