I have the following SQL statement
SELECT invoices.id, invoices.companyid IF( comp_companies.id = invoices.companyid, comp_companies.name, 'Deleted company' ) AS companyname
FROM invoices, comp_companies
WHERE invoice_name IS NULL
LIMIT 0 , 30
and I have 17 elements in my invoices table, 16 where invoice_name is null.
What I want to achieve is to select everything from invoices where invoice_name is NULL, and get the name of the company which is attached by a company id, directly from the query, or if there is no such company id in comp_companies table, get the text "Deleted Company" at the companyname.
This query returns 32 results, double the amount that are in the invoices table, two for each distinct invoice id, one with companyname as Deleted Company and one with companyname as the actual company name.
I already tried grouping by invoices.id, or selecting distinct invoices.id only, but nothing worked.
Can someone tell me what is the "problem" with my query, and how could I achieve the desired result?