0

I'm trying to create a SQL query that tells me how many users there are that have one or more products.

I created this query which tells me all of the users that have products:

SELECT DISTINCT `users`.*
FROM `users`
INNER JOIN `products`
ON `users`.`id` = `products`.`creator_id`

However, I want the count of the users, not the users themselves.

So I created this query which uses the COUNT() function

SELECT DISTINCT COUNT(*)
FROM `users`
INNER JOIN `products`
ON `users`.`id` = `products`.`creator_id`

But I believe I'm using the COUNT incorrectly because this query returns 164 which is a lot more than the previous query returned.

3 Answers 3

4
SELECT COUNT(DISTINCT `users`.`id`)
FROM `users`
INNER JOIN `products`
ON `users`.`id` = `products`.`creator_id`
Sign up to request clarification or add additional context in comments.

Comments

1

DISTINCT filters your result rows to be unique. The aggregation (i.e. the COUNT()) is done prior, so is following your JOIN and counting users twice.

So, to get the number of users that have products, you could do:

SELECT      COUNT(DISTINCT u.id)

FROM        users    AS u

INNER JOIN  products AS p
    ON      u.id = p.creator_id

Similarly, you could do something a bit useful, like the count of products per user:

SELECT      u.id,
            COUNT(*) AS ProductCount

FROM        users    AS u

INNER JOIN  products AS p
    ON      u.id = p.creator_id

GROUP BY    u.id

Comments

1

The following query may be more efficient:

SELECT COUNT(*)
FROM `users` u
WHERE exists (select 1 from `products` p where u.id = p.creator_id);

Performance will be best with an index on product(creator_id). And, performance will be better than the join/count(distinct) version when some users have many products.

1 Comment

Oh EXISTS you're so efficient and underutilized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.