Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select count

Tags:

mysql

count

I am trying to count the number of companies that have at least one product from the following query

SELECT count(*)
FROM company c
JOIN product p on c.id = product.company_id
WHERE p.is_deleted = 0
AND c.is_customer = 1
AND c.company_type_id = 5
GROUP by c.id

So, this shows me a list of all companies, and the count of products for each company.

What I am trying to achieve is a count of companies from the above result.

This can be achieved as follows:

SELECT count(*)
FROM ( 
    SELECT count(*)
    FROM company c
    JOIN product p on c.id = product.company_id
    WHERE p.is_deleted = 0
    AND c.is_customer = 1
    and c.company_type_id = 5
    GROUP by c.id) AS t1

So, this gives me the correct result, but I am just wondering if there is a more efficient way of doing things.

like image 958
JonoB Avatar asked Mar 16 '11 11:03

JonoB


People also ask

What is SELECT COUNT (*) as COUNT in MySQL?

COUNT(*) The COUNT(*) function returns the number of rows in a dataset using the SELECT statement. The function counts rows with NULL, duplicate, and non-NULL values. You can also use the WHERE clause to specify a condition.

Can I use SELECT in COUNT?

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).

What does SELECT COUNT (*) mean?

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates. COUNT(ALL expression) evaluates expression for each row in a group, and returns the number of nonnull values.

What does SELECT COUNT (*) mean in SQL?

The COUNT(*) function counts the total rows in the table, including the NULL values.


1 Answers

I believe you can simplify it to this:

SELECT count(distinct c.id)
FROM company c
JOIN product p on c.id = product.company_id
WHERE p.is_deleted = 0
AND c.is_customer = 1
AND c.company_type_id = 5
like image 148
Blorgbeard Avatar answered Oct 28 '22 07:10

Blorgbeard