我使用MySQL COUNT()
方法找出两个表中有多少行具有u.id的uid
。
为此,我使用以下方法:
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
来自answers
的示例数据:http://d.pr/i/TMkU
来自questions
的示例数据:http://d.pr/i/tuwU
答案 0 :(得分: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'
答案 1 :(得分: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'