MySQL:在其他表中计数

MySQL: Count in other tables

在我的 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)
);

现在我想select一些位置并以高效的方式计算评分数、平均星数和收藏数。

我的方法是这个,但它给了我完全错误的 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

你能帮帮我吗?

问题与您使用 OR 的连接条件有关:

WHERE (l.id=r.location_id OR l.id=f.location_id)

当它在 l.id = r.location_id 处找到一条记录时,由于 OR,它对 f 中的所有行都为真。同样,当它找到 1 条带有 l.id = f.location_id 的记录时,您将匹配 r.

中的所有行

相反,对每个 rf 使用 LEFT JOIN

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