2013-05-31 42 views
1

我有一張表(n2m),其中包含作者的ID及其文章的ID。我在統計表中只有一篇文章的作者數量。我使用下面的查詢:只計算一篇文章的作者數

select count(*) from authors_articles 
where AutID in 
    (
    select AutID 
    from authors_articles 
    group by AutID 
    having count(distinct articleID) = 1 
    ) 

現在,我想知道如果我的查詢是正確的,並且在任何情況下,我可以提高此查詢,使其更快!?

非常感謝,

回答

3

您的查詢可以簡化爲:

select count(*) from 
    (
    select AutID 
    from authors_articles 
    group by AutID 
    having count(distinct articleID) = 1 
    ) x 
0

我認爲它可以更簡單:

SELECT count(*) num_articles 
FROM authors_articles 
GROUP BY AutID 
HAVING num_articles = 1 
+0

這是不正確的 - num_articles將是返回的行數。 OP需要聚合中只有1行返回的行數(GROUP BY) – jmadsen

0

您所查詢的是正確的。

MySQL恰好實例化子查詢並且對於group by的方法效率低下。如果您對authors_articles(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; 

但這一個left outer join匹配創作者,他們可能已經編寫任何其他物品。如果沒有,那麼作者有一篇文章,並且聚合計數。

這可能有效。它可能表現更好,在正確的環境下可能真的非常重要。但總的來說,我會堅持你的查詢,因爲我發現它的意圖更清晰。

相關問題