MySQL Forums
Forum List  »  Performance

Re: optimizing count statement
Posted by: Felix Geerinckx
Date: October 12, 2005 08:23AM

Karolis wrote:

> SELECT COUNT(*) FROM (
> SELECT 1 FROM INDEX_KEYS WHERE KeywordID IN (7, 8) GROUP BY DocumentID HAVING COUNT(DISTINCT KeywordID) = 2) AS x;
> +----------+
> | COUNT(*) |
> +----------+
> | 6204 |
> +----------+
> 1 row in set (0.04 sec)
>
>
> goodness :))))))))
> Can you please explain why this is happening?

Well, you just eliminated a join (the outer SELECT is optimized away).

The subquery finds all documents that are associated with both KeywordIDs 7 and 8.
Since you just want to count the number of rows, you write SELECT 1 ...

By the way, this works with any number of KeywordIDs, as long as you adjust the 2 in the HAVING clause accordingly.

--
felix
Please use BBCode to format your messages in this forum.

Options: ReplyQuote


Subject
Views
Written By
Posted
3931
October 11, 2005 11:30AM
1835
October 12, 2005 04:56AM
1760
October 12, 2005 06:31AM
1439
October 12, 2005 07:11AM
1639
October 12, 2005 07:40AM
1557
October 12, 2005 07:53AM
1729
October 12, 2005 07:50AM
1710
October 12, 2005 08:01AM
1700
October 12, 2005 08:05AM
Re: optimizing count statement
1432
October 12, 2005 08:23AM
1722
October 12, 2005 08:22AM
1671
October 12, 2005 08:38AM
1799
October 12, 2005 08:46AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.