0

因为我正在制作一个简单的论坛,比如关注者和关注者,所以我有以下表格。

users

 1. id
 2. name

questions

 1. id
 2. description
 3. user_id//foreign key of users.id

answers

 1. id
 2. question_id//foreign key of questions.id
 3. description
 4. user_id//foreign key of users.id

follow

 1. from_user(which user)//foreign key of users.id
 2. to_user(following to which user)//foreign key of users.id

我的查询如下

SELECT users.id, users.name, count(DISTINCT questions.id), count(answers questions.id), count(follow1.from_user), count(follow2.to_user) from users LEFT JOIN questions ON users.id = questions.user_id LEFT JOIN answers ON users.id = answers.user_id LEFT JOIN follow as follow1 ON users.id = follow1.from_user LEFT JOIN follow as follow2 ON users.id = follow2.to_user WHERE users.id = 1

这可以正常工作并给出正确的结果。

但是当使用相同的查询时,我将 WHERE IN 的子句如下

SELECT users.id, users.name, count(DISTINCT questions.id), count(answers questions.id), count(follow1.from_user), count(follow2.to_user) from users LEFT JOIN questions ON users.id = questions.user_id LEFT JOIN answers ON users.id = answers.user_id LEFT JOIN follow as follow1 ON users.id = follow1.from_user LEFT JOIN follow as follow2 ON users.id = follow2.to_user WHERE users.id IN (1, 3)

它只显示用户 id 1 的记录。不是 3。但是谈论上一个查询对两者都很好,id's并显示正确的记录。

4

1 回答 1

1

这是一个奇怪的问题,我只能建议使用GROUP BY users.id,以便 mysql 不会在所有记录中组合 count()s。希望在某种程度上有所帮助。

于 2012-07-02T12:27:28.650 回答