MySQL:在其他表中计数

时间:2015-02-24 19:05:13

标签: mysql database count

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

你能帮助我吗?

1 个答案:

答案 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 JOINr分别使用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