4

我正在使用 MySQLCOUNT()方法来找出两个表中有多少行具有uidu.id。

为此,我使用以下方法:

SELECT u.id, u.first_name, u.last_name, u.email, u.username, COUNT( q.uid ) AS  `q_count`, COUNT( a.uid ) AS `a_count` 
FROM  `users` AS u
INNER JOIN `questions` AS q ON u.id = q.uid
INNER JOIN `answers` AS a ON u.id = a.uid
WHERE u.username =  'admin'

但是,当我运行上述查询时,第二个计数返回的行数与第一个计数的行数相同。我知道这一点,因为第一个计数返回两个,第二个也做同样的事情,当表中有两行和questions表中有一行时answers

请你能告诉我哪里出错了吗?

谢谢


我收到的样本:http: //d.pr/i/vcnJ

样本数据来自answershttp ://d.pr/i/TMkU

样本数据来自questionshttp ://d.pr/i/tuwU

4

2 回答 2

1

我相信原因是您正在执行 JOIN,它将将结果合并为一个。请使用相同的查询,但SELECT *改为使用,您会明白为什么会发生这种情况。

试试这个:

SELECT u.id, u.first_name, u.last_name, u.email, u.username, COUNT( DISTINCT q.id ) AS  `q_count`, COUNT( DISTINCT a.id ) AS `a_count` 
FROM  `users` AS u
INNER JOIN `questions` AS q ON u.id = q.uid
INNER JOIN `answers` AS a ON u.id = a.uid
WHERE u.username =  'admin'
于 2012-04-29T14:38:42.190 回答
0

您不能在一个查询中计算两个表。COUNT()计算行数,而不是特定值。

但是,您可以做的是

SELECT u.id, u.first_name, u.last_name, u.email, u.username, 
SUM( CASE WHEN q.uid IS NULL THEN 0 ELSE 1 END ) AS  `q_count`, 
SUM( CASE WHEN a.uid IS NULL THEN 0 ELSE 1 END ) AS `a_count` 
FROM  `users` AS u
LEFT JOIN `questions` AS q ON u.id = q.uid
LEFT JOIN `answers` AS a ON u.id = a.uid
WHERE u.username =  'admin'
于 2012-04-29T14:38:14.800 回答