从子表中选择计数

时间:2014-01-31 05:05:03

标签: mysql performance select join count

我需要从查询中涉及的一个子表/连接表中获取计数。我将用一个简单的例子来演示:

表:用户

    id             name            etc
-------------------------------------------
    1               u1
    2               u2

表:练习

    id             userId            etc
-------------------------------------------
    1               1
    2               1

现在我需要从用户表中选择idnameetc等各个字段以及exercise表<中各种用户ID的计数/ strong>即可。

例如,在上述情况下,我需要输出

    id             name            count
-------------------------------------------
    1               u1               2 --since two u1's are present in exercise
    2               u2               0 --since no u2's are present in exercise

我试过这个:但是我得到了语法错误:

--actual query is very complex
SELECT u.id, u.name, COUNT(e.*)
FROM   user AS u
JOIN   exercise AS e ON u.id =  e.userId 

我尝试了这个:但我再次遇到语法错误:

--actual query is very complex
SELECT u.id, u.name, (SELECT COUNT(*) FROM e)
FROM   user AS u
JOIN   exercise AS e ON u.id =  e.userId 

这可以作为子查询使用,但速度很慢(每个表中大约10000行的时间为5到13秒):

--actual query is very complex
SELECT u.id, u.name, (SELECT COUNT(*) FROM exercise WHERE e.userId = u.id)
FROM   user AS u

我是否有办法在count左右的帮助下在一个查询中获取join个信息?子查询对我的需求来说非常慢。

2 个答案:

答案 0 :(得分:4)

尝试使用GROUP BY,如下所示:

SELECT u.id, u.name, COUNT(e.userId)
FROM   user AS u
LEFT JOIN exercise AS e 
ON u.id =  e.userId
GROUP BY u.id 

答案 1 :(得分:1)

试试这个:

SELECT u.id, u.name, COUNT(e.userId)
FROM  user AS u
LEFT JOIN exercise AS e 
ON u.id =  e.userId
GROUP BY u.id,u.name

即使user表中没有记录,左连接仍将从exercise表返回行。