在我的MySQL数据库中我有三个表:
CREATE TABLE favorites (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) NOT NULL,
location_id int(11) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE locations (
id int(20) NOT NULL,
`name` varchar(150) NOT NULL,
pos_lat float NOT NULL,
pos_lon float NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE ratings (
id int(11) NOT NULL AUTO_INCREMENT,
location_id int(11) NOT NULL,
user_id int(11) NOT NULL
stars int(11) NOT NULL,
review text,
PRIMARY KEY (id)
);
现在我想选择一些位置,并以有效的方式计算评分数,平均星数和收藏数。
我的方法是这个,但它给了我完全错误的COUNT值。
SELECT l.id AS location_id,
COUNT(DISTINCT r.id), AVG(r.stars), COUNT(DISTINCT f.id)
FROM locations l, ratings r, favorites f
WHERE (l.id=r.location_id OR l.id=f.location_id)
AND l.id IN (7960,23713,...,18045,24247)
GROUP BY l.id
你能帮助我吗?
答案 0 :(得分:1)
问题与使用OR的加入条件有关:
WHERE (l.id=r.location_id OR l.id=f.location_id)
当找到一条记录l.id = r.location_id
时,由于OR
,f中的所有行都为真。类似地,当它找到带有l.id = f.location_id
的1条记录时,您将匹配r。
相反,LEFT JOIN
和r
分别使用f
:
SELECT l.id AS location_id,
COUNT(DISTINCT r.id), AVG(r.stars), COUNT(DISTINCT f.id)
FROM locations l
LEFT JOIN ratings r ON (l.id = r.location_id)
LEFT JOIN favorites f ON (l.id = f.location_id)
WHERE l.id IN (7960,23713,...,18045,24247)
GROUP BY l.id