0

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.

grepsedawk
  • 3,324
  • 2
  • 26
  • 49
J.B.J.
  • 440
  • 1
  • 8
  • 15

1 Answers1

1
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.

Community
  • 1
  • 1
Frederick Zhang
  • 3,593
  • 4
  • 32
  • 54