我有以下查询,就像我想要的那样,除了我想返回一个伪(?)列,每个属性具有从内连接匹配的单元数。其中p.team = u.team和u.deleted ='0000-00-00 00:00:00'和u.rates!='0'。我可以在同一个查询中执行此操作吗?
一个房产有几个单位。他们都附属于“团队”(想想用户名)。
SELECT DISTINCT p.title, p.state, p.city, p.regionID, p.team, p.type, p.lat, p.lng, p.url_title
FROM Properties AS p
INNER JOIN Units AS u ON p.team = u.team
INNER JOIN Rates AS r ON p.team = r.team
INNER JOIN Photos AS ph ON p.team = ph.team
AND p.public = '1'
AND u.rates != '0'
AND p.deleted = '0000-00-00 00:00:00'
AND u.deleted = '000-00-00 00:00:00'
AND r.deleted = '000-00-00 00:00:00'
AND ph.deleted = '000-00-00 00:00:00'
GROUP BY p.id
ORDER BY p.created ASC
答案 0 :(得分:0)
由于您只有一个聚合,并且您似乎按Properties
行进行分组,因此这应该相对容易。你的意思是这样的(未经测试)?
SELECT p.title, p.state, p.city, p.regionID, p.team, p.type, p.lat, p.lng,
p.url_title , COUNT(u.*) AS number_of_units
FROM Properties AS p
INNER JOIN Units AS u ON p.team = u.team
INNER JOIN Rates AS r ON p.team = r.team
INNER JOIN Photos AS ph ON p.team = ph.team
AND p.public = '1'
AND u.rates != '0'
AND p.deleted = '0000-00-00 00:00:00'
AND u.deleted = '000-00-00 00:00:00'
AND r.deleted = '000-00-00 00:00:00'
AND ph.deleted = '000-00-00 00:00:00'
GROUP BY p.id, p.title, p.state, p.city, p.regionID, p.team, p.type, p.lat, p.lng, p.url_title
ORDER BY p.created ASC
根据您的意思,您可能需要执行COUNT(DISTINCT(u.id))
。你的问题很难说清楚。
作为参考,“困难的方法”是创建一个子查询来加入以进行计数。您可能需要这样做来计算多个不相关的项目,或者按一个事物分组并按另一个事项计数:
SELECT DISTINCT p.title, p.state, p.city, p.regionID, p.team, p.type, p.lat, p.lng,
p.url_title, uuCount.number_of_units
FROM Properties AS p
INNER JOIN Units AS u ON p.team = u.team
INNER JOIN Rates AS r ON p.team = r.team
INNER JOIN Photos AS ph ON p.team = ph.team
AND p.public = '1'
AND u.rates != '0'
AND p.deleted = '0000-00-00 00:00:00'
AND u.deleted = '000-00-00 00:00:00'
AND r.deleted = '000-00-00 00:00:00'
AND ph.deleted = '000-00-00 00:00:00'
INNER JOIN
(
SELECT uu.team, COUNT(*) AS number_of_units
FROM Units uu
WHERE uu.deleted = '0000-00-00 00:00:00'
AND u.rates != '0'
GROUP BY uu.team
) AS uuCount ON p.team = uuCount.team
GROUP BY p.id
ORDER BY p.created ASC