Mysql 仅凭一篇文章计算作者
我有一个表(n2m),其中包含作者ID和他们的文章ID。我在统计只有一篇文章的作者数量。我正在使用以下查询:Mysql 仅凭一篇文章计算作者,mysql,sql,Mysql,Sql,我有一个表(n2m),其中包含作者ID和他们的文章ID。我在统计只有一篇文章的作者数量。我正在使用以下查询: select count(*) from authors_articles where AutID in ( select AutID from authors_articles group by AutID having count(distinct articleID) = 1 ) 现在,我想知道我的查询是否正确,在任何情
select count(*) from authors_articles
where AutID in
(
select AutID
from authors_articles
group by AutID
having count(distinct articleID) = 1
)
现在,我想知道我的查询是否正确,在任何情况下,我是否可以改进此查询以使其更快
非常感谢,您的查询可以简化为:
select count(*) from
(
select AutID
from authors_articles
group by AutID
having count(distinct articleID) = 1
) x
我认为可以更简单:
SELECT count(*) num_articles
FROM authors_articles
GROUP BY AutID
HAVING num_articles = 1
你的问题是正确的
MySQL碰巧实例化了子查询,并且对于groupby
的方法效率低下。如果您在作者文章(autId,articleId)
上有一个索引,那么以下内容的性能可能会更好:
select count(*)
from authors_articles aa left outer join
authors_articles aa1
on aa.autId = aa1.autId and
aa.articleId <> aa1.articleId
where aa1.autId is NULL;
选择计数(*)
来自作者的文章aa左外连接
作者和文章aa1
在aa.autId=aa1.autId和
aa.articleId aa1.articleId
其中aa1.autId为空;
这将执行一个左外部联接
,以将作者与他们可能编写的任何其他文章相匹配。如果没有,则作者有一篇文章,聚合计算该文章
这可能有用。它可能表现得更好,在适当的情况下,这可能非常非常重要。不过,一般来说,我会坚持使用您的查询,因为我发现它的意图更清楚。这是错误的-num_articles将是返回的行数。OP需要返回的行数,聚合中只有一行(分组依据)