我有一个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,所以我想知道查询中有什么问题,为什么没有包含它。
任何帮助,为什么这不是返回预期的结果和我必须做什么,以获得预期的结果,是非常感谢的。
发布于 2014-03-25 23:08:37
您正在按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只会减慢进程。
发布于 2014-03-25 23:09:38
社区位于多个地图区域。你打算怎么处理呢?
您的外部查询确实不需要。您可以将查询表述为:
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;https://stackoverflow.com/questions/22648173
复制相似问题