MySQL子查询未返回预期结果

时间:2014-03-25 23:04:12

标签: php mysql

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

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

我正在为地图区域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

当我对地图区域601和606运行上述查询时,我得到以下内容,这对某些社区来说是正确的,但未列出Solera社区:

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

由于Solera的行数最多,地图区域为606 - Henderson,我想知道查询中为什么没有包含它是错误的。

为什么没有返回预期结果以及我必须做些什么来获得预期结果的任何帮助都非常感谢。

2 个答案:

答案 0 :(得分:0)

您按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只会减慢进程的速度

答案 1 :(得分:0)

社区位于多个地图区域。你打算如何处理?

您的外部查询确实不需要。您可以将查询短语描述为:

SELECT community, mapArea
FROM single_family
WHERE mapArea LIKE '601%' OR mapArea LIKE '606%'
GROUP BY community
ORDER BY community;

如果您希望将所有mapArea列为一列,请使用group_concat()

SELECT community, group_concat(mapArea) as MapAreas
FROM single_family
WHERE mapArea LIKE '601%' OR mapArea LIKE '606%'
GROUP BY community
ORDER BY community;

如果您满足于将它们放在不同的行上,请在group by

中添加该列
SELECT community, mapArea
FROM single_family
WHERE mapArea LIKE '601%' OR mapArea LIKE '606%'
GROUP BY community, MapArea
ORDER BY community;