一个更有效的MySQL语句?

时间:2010-11-17 11:59:43

标签: mysql

我有这个mysql可行,但我不禁想到有更好的方法吗?

SELECT u.username, count( c.username ) AS intImageCount
FROM users u
JOIN content c ON c.username = u.username
WHERE (SELECT count( username )FROM content WHERE username = c.username) > 0
GROUP BY u.username

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

尝试使用HAVING而不是

这样的东西
SELECT u.username, count( c.username ) AS intImageCount 
FROM users u 
JOIN content c ON c.username = u.username 
GROUP BY u.username
HAVING count( c.username ) > 0

查看SELECT Syntax

答案 1 :(得分:2)

而不是HAVING,你的(INNER) JOIN已经成功了 您可以完全删除子查询。

SELECT   u.username
         , count( c.username ) AS intImageCount
FROM     users u
         INNER JOIN content c ON c.username = u.username
GROUP BY u.username

答案 2 :(得分:0)

您没有看到子选择的需要并使用LEFT JOIN:

SELECT u.username, count( c.username ) AS intImageCount
FROM users u
LEFT JOIN content c ON c.username = u.username
GROUP BY u.username