我正在使用这个MySQL语句来查找社区的平均财产评估。问题是我必须为每个邻域添加一个SELECT语句 - 并且有很多邻域。有没有办法做到这一点,而无需指定'RIVER FRONT'或'OLD TOWN'?有更有效的方法吗?
SELECT AVG(property_table.assessment)
FROM property_table, neighborhood_table
WHERE property_table.id = neighborhood_table.id AND neighborhood_table.neighborhood = 'RIVER FRONT'
UNION ALL
SELECT AVG(property_table.assessment)
FROM property_table, neighborhood_table
WHERE property_table.id = neighborhood_table.id AND neighborhood_table.neighborhood = 'OLD TOWN'
答案 0 :(得分:1)
这是一个标准的SQL聚合语句,显示所有邻域的平均值 左连接允许您获得零值,其中邻域中不存在属性。
SELECT
n.neighborhood, COALESCE(AVG(p.assessment), 0)
FROM
neighborhood_table n
LEFT JOIN
property_table p ON p.id = n.id
GROUP BY
n.neighborhood;
答案 1 :(得分:0)
SELECT AVG(property_table.assessment), neighborhood_table.neighborhood
FROM property_table
INNER JOIN neighborhood_table ON property_table.id = neighborhood_table.id
WHERE neighborhood_table.neighborhood IN ('RIVER_FRONT', 'OLD TOWN')
GROUP BY neighborhood_table.neighborhood;