我有一个类似于以下的表格:
domain | file | Number
------------------------------------
aaa.com | aaa.com_1 | 111
bbb.com | bbb.com_1 | 222
ccc.com | ccc.com_2 | 111
ddd.com | ddd.com_1 | 222
eee.com | eee.com_1 | 333
我需要查询共享相同Number
且File
名称以_1
结尾的Domains
数量>。我尝试了以下方法:
select count(domain) as 'sum domains', file
from table
group by Number
having
count(Number) >1 and File like '%\_1';
它给了我:
sum domains | file
------------------------------
2 | aaa.com
2 | bbb.com
我希望看到以下内容:
sum domains | file
------------------------------
1 | aaa.com
2 | bbb.com
因为Number
111在File
以_1
和_2
结尾出现一次,所以应该算1仅有的。我怎样才能正确应用我之前所说的两个条件?
最佳答案
如 SELECT
语法中所述:
The
HAVING
clause is applied nearly last, just before items are sent to the client, with no optimization.
换句话说,它在执行分组操作之后应用(与WHERE
相反,后者在任何分组之前执行手术)。请参阅WHERE vs HAVING .
因此,您当前的查询首先根据以下内容形成结果集:
SELECT COUNT(domain) AS `sum domains`, file
FROM `table`
GROUP BY Number
查看 sqlfiddle :
| SUM DOMAINS | FILE | --------------------------- | 2 | aaa.com_1 | | 2 | bbb.com_1 | | 1 | eee.com_1 |
As you can see, the values selected for the file
column are merely one of the values from each group—as documented under MySQL Extensions to GROUP BY
:
The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.
Your current query then proceeds to filter these results according to your HAVING
clause:
HAVING COUNT(Number) > 1 AND file LIKE '%\_1'
使用上面选择的file
值,每个组都符合第二个条件;前两组根据第一个标准进行匹配。因此结果为the complete query是:
| SUM DOMAINS | FILE | --------------------------- | 2 | aaa.com_1 | | 2 | bbb.com_1 |
Following your comments above, you want to filter the records on file
before grouping and then filter the resulting groups for those containing more than one match. Therefore use WHERE
and HAVING
respectively (and select Number
instead of file
to identify each group):
SELECT Number, COUNT(*) AS `sum domains`
FROM `table`
WHERE file LIKE '%\_1'
GROUP BY Number
HAVING `sum domains` > 1
查看 sqlfiddle :
| NUMBER | SUM DOMAINS | ------------------------ | 222 | 2 |
关于mysql - 如何在having子句中提出两个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309290/