Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySQL Select Count of Duplicate Value In Relation Table

I have 3 tables: foods, order_detail, and orders

Here are the records for table foods:

id    | name       | type
------------------------------
F01   | Omelette   | Breakfast
F02   | Burger     | Breakfast
F03   | Satay      | Lunch
F04   | Fried Rice | Dinner

Here are the records for table order_detail:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

food_id    | order_id
-----------------------------
F01        | T01
F04        | T01
F02        | T02
F03        | T03
F03        | T04

And here are the records for orders table:

order_id    | date       | qty
---------------------------------
T01         | 2017-05-01 | 2
T02         | 2017-05-02 | 1
T03         | 2017-05-05 | 1
T04         | 2017-05-07 | 1

I want to show count order detail grouped by food type. I expected this result:

type       | total_order
-------------------------
Breakfast  | 2
Lunch      | 2
Dinner     | 1

Here is my approach, but it still doesn’t show the expected result.

SELECT
f.type,
(SELECT COUNT(*) FROM order_detail od WHERE f.id = od.food_id) AS total_order
FROM foods f
LEFT JOIN order_detail od ON f.id = od.food_id
GROUP BY f.type
ORDER BY f.id

The result is:

type       | total_order
-------------------------
Breakfast  | 1
Lunch      | 2
Dinner     | 1

How can I get the result I want? Thanks in advance!

>Solution :

Aggregation can work here, but you need to join across all three tables:

SELECT f.type, COUNT(o.order_id) AS total_order
FROM foods f
LEFT JOIN order_detail od ON od.food_id = f.id
LEFT JOIN orders o ON o.order_id = od.order_id
GROUP BY f.type
ORDER BY f.id;

Note that we do a left join across all three tables in order to not drop any food type which might happen to have zero orders.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading