简体   繁体   中英

MySQL Group By removes single results?

i have 3 tables that i am joining together. It works great if the data is present in all 3 tables, but in this case, it would return 3 of each row due to how the joining works i assume.

So, in order to get rid of the duplicates, i GROUP BY the name, leaving 1 of each unique row left, which is great.

HOWEVER, if the third table is EMPTY it returns NO rows at all. If i remove the GROUP BY part, it returns 1 of each row.

So my question is 2-fold: 1. Why is this happening? 2. How do i fix it?

In short, the question is: "Why does MySQL remove the rows if only 1 of each is found, when using group by".

For instance if i get these names back: Car Phone TV

And i go a group by name, it returns nothing at all. if it is like this:

Car
Phone
TV
Car
Phone
TV

The group by works as expected and leaves me with 1 of each.

Here is the SQL (With the group-by at the end):

SELECT name, amount, amount_left
FROM `template_useages_products`
JOIN products ON template_useages_products.product_id = products.id 
JOIN leftovers ON leftovers.template_useages_id = template_useages_products.template_useages_id
WHERE template_useages_products.template_useages_id = ?
GROUP BY name

Thanks in advance.

SELECT
    name, amount, amount_left
FROM
    template_useages_products
    LEFT JOIN products ON template_useages_products.product_id = products.id
    LEFT JOIN leftovers ON leftovers.template_useages_id = template_useages_products.template_useages_id
WHERE
    template_useages_products.template_useages_id = ?
GROUP BY
    name

Use LEFT JOIN instead. JOIN refers to INNER JOIN by default in MySQL, which means that results will be excluded if any of the tables lacks a matching record. Ref

By using LEFT JOIN , those columns in the final result table will be filled with NULL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM