mysql - 如何在having子句中提出两个条件

标签 mysql

我有一个类似于以下的表格:

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

我需要查询共享相同NumberFile名称以_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/

相关文章:

c# - 在 C# 中保护用户指定的表名免受 SQL 注入(inject)

mysql - '' 附近的 SQL 语法错误

javascript - 执行 'COUNT(id)' 查询后,无法从 RowDataPacket 访问 'SELECT COUNT'

mysql - 如何在 1 个 sql 查询中从 4 个表中获取数据?

php - 使用 AngularJs 在 mySql 数据库中插入数据

php - 查询不会保存

mysql - 如何将mysql中的查询结果保存到带有列名的excel文件中

Mysql连接三表问题

mysql - 内部连接和用逗号分隔的表有什么区别吗?

mysql - 如果使用 group by 和 LEFT JOIN 不存在行,则计为零