我的表定义如下:
placeid
是Place
table的id的外键。在那张桌子上,我想得到这样的信息:
- placeid, place name, totalReview, totalFavorite, totalPhoto.
我被困了。我目前的进展我可以从1个表中获取信息,就像我可以通过使用这个mysql语句知道totalReview of place:
SELECT p.*, count(r.id) as totalReview from Place p left join Review r on p.id = r.placeid group by p.id
。
但是,我不知道如何得出totalFavorite和totalPhoto。
答案 0 :(得分:4)
您需要单独聚合每个表。这是一个解决方案:
SELECT p.*,
totalreview,
totalfavorite,
totalphoto
FROM place p
LEFT OUTER JOIN (SELECT placeid,
Count(*) AS totalReview
FROM review
GROUP BY placeid) r
ON p.placeid = r.placeid
LEFT OUTER JOIN (SELECT placeid,
Count(*) AS totalFavorite
FROM favorite
GROUP BY placeid) f
ON p.placeid = f.placeid
LEFT OUTER JOIN (SELECT placeid,
Count(*) AS totalPhoto
FROM photo
GROUP BY placeid) ph
ON p.placeid = ph.placeid
答案 1 :(得分:0)
这是一种简单的方法:
SELECT
p.id, p.name,
(SELECT COUNT(*) FROM Review r WHERE r.placeId=p.id) AS totalReview
(SELECT COUNT(*) FROM Favorite f WHERE f.placeId=p.id) AS totalFavorite
(SELECT COUNT(*) FROM Photo ph WHERE ph.placeId=p.id) AS totalPhoto
FROM Place p