php - MySQL 子查询未返回预期结果

标签 php mysql

我有一个 MySQL 表,其中包含社区及其对应的 MLS map 区域。有些社区很大,占据了多个 map 区域。

我正在尝试执行一个查询,在传递多个 map 区域时返回最常见的社区及其 map 区域。

我正在为 map 区域 601 和 606 尝试的查询是:

SELECT DISTINCT(community), mapArea FROM (
    SELECT community, mapArea
    FROM single_family
    GROUP BY community
    ORDER BY COUNT(community) DESC) AS query1
WHERE mapArea LIKE '601%' OR mapArea LIKE '606%' ORDER BY community

示例 single_family 表布局(实际表有超过 60k 行):

community    mapArea
Solera       606 - Henderson
Solera       606 - Henderson
Solera       204 - East
Solera       606 - Henderson
Solera       202 - East
Anthem       606 - Henderson
Green Valley 601 - Henderson
Green Valley 601 - Henderson
Green Valley 606 - Henderson
Seven Hills  606 - Henderson
Seven Hills  606 - Henderson

如果我对表格进行计数,它会显示:

community      mapArea           countCommunity
Anthem         606 - Henderson   776
Solera         606 - Henderson   58
Solera         204 - East        6
Solera         202 - East        1
Green Valley   601 - Henderson   188
Green Valley   606 - Henderson   117
Seven Hills    606 - Henderson   372

当我对 map 区域 601 和 606 运行上述查询时,我得到以下对于某些社区是正确的但未列出例如 Solera 社区的信息:

community     mapArea
Anthem        606 - Henderson
Green Valley  601 - Henderson
Seven Hills   606 - Henderson

由于 Solera 的行数最多, map 区域为 606 - Henderson,我想知道查询中有什么问题导致它没有被包括在内。

对于为什么这没有返回预期结果以及我必须做什么才能获得预期结果的任何帮助,我们都非常感谢。

最佳答案

您正在按 community 分组,结果可能会在分组行中隐藏 mapArea 行。试试这个:

SELECT community, mapArea FROM (
    SELECT community, mapArea
    FROM single_family
    WHERE mapArea LIKE '601%' OR mapArea LIKE '606%' 
    GROUP BY community
    ORDER BY COUNT(community) DESC) AS query1
ORDER BY community

另外,当您真正按同一列分组时,为什么要使用 DISTINCT?子查询将产生具有不同社区值的行。使用 DISTINCT 只会减慢进程

关于php - MySQL 子查询未返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22648173/

相关文章:

PHP/MYSQL验证

c# - ASP :gridview filter using listbox cannot make multiple selection

php - 使用php将Mysql日期转换为JSON中的毫秒

php - 登录成功后显示用户名

php - Laravel 5.4.24 在用户注销期间抛出 MethodNotAllowedHttpException

PHP-echo 中的 JavaScript 不明显

mysql - 按天对记录进行分组,包括在 MySQL 中不包含记录的天数

php - MySQL 全文搜索不适用于特定单词

php - Memcached 忽略 OPT 超时

php - 使用 for each 循环在 MySQL 数据库中插入多个图像