2012-07-02 28 views
0

因为我正在做一个简单的论坛,像跟随者和跟随的twitter的触摸,我有以下表格。mysql左连接和查询与条款中显示只有1行的地方

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 

这工作正常,并给出了正确的结果。

但与相同的查询我把凡条款如下

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并显示正确的记录。

回答

1

这是一个奇怪的,我只能建议使用GROUP BY users.id,以便mysql不会将count()组合到所有记录上。希望以某种方式帮助。

+0

噢我的我的我的..!这真的是最糟糕的。因为大约1年前,我知道这一点,现在我忘了它。我不知道该说什么。无论如何非常感谢。我对自己感到非常失望。 – KuKu

+0

:D新鲜(ISH)眼睛看着一个问题就是这样。 –