I have a query with joins and subquery (derived table). If I run it without LIMIT 1 the result will contain the vat and the id field with the proper values.
The first query:
SELECT i.id, i.vat, pl.invoice_id as inv_id, pl.product_id as pl_id, pl.quantity as qty, pl.price, pl.currency, p.name, p.manufacturer, p.list_price, p.cost_price, p.wholesale_price, p.cikkszam, p.unit, p.group_name
FROM soulnsoda_products_log pl
LEFT JOIN soulnsoda_products p ON pl.product_id=p.id
LEFT JOIN (select id, vat, parent_id, beneficiary_account from soulnsoda_invoices) as i ON i.parent_id>0 AND pl.invoice_id=i.parent_id AND pl.product_id=i.beneficiary_account
WHERE pl.action=6 AND p.cikkszam = 'S6511415-BLK' AND (pl.stamp BETWEEN '2015-08-15 00:00:00' AND '2015-08-15 23:59:59') AND pl.warehouse_name='Garage - Árkád'
ORDER BY p.cikkszam
The result will contain the i.id and i.vat fields with values, but duplicating rows:
id vat inv_id pl_id qty price name
93119 27.00 93117 21961 -1.00 1096.85 HUF SUPRA ICON SX BLACK DB
93120 27.00 93117 21961 -1.00 1096.85 HUF SUPRA ICON SX BLACK DB
93119 27.00 93117 21961 -1.00 1096.85 HUF SUPRA ICON SX BLACK DB
93120 27.00 93117 21961 -1.00 1096.85 HUF SUPRA ICON SX BLACK DB
I have to filter out rows with duplicated ids. When I'm using LIMIT 1 the duplication will be gone but the id and the vat field will be NULL. And I don't know why...
The second query with LIMIT:
SELECT i.id, i.vat, pl.invoice_id as inv_id, pl.product_id as pl_id, pl.quantity as qty, pl.price, pl.currency, p.name, p.manufacturer, p.list_price, p.cost_price, p.wholesale_price, p.cikkszam, p.unit, p.group_name
FROM soulnsoda_products_log pl
LEFT JOIN soulnsoda_products p ON pl.product_id=p.id
LEFT JOIN (select id, vat, parent_id, beneficiary_account from soulnsoda_invoices LIMIT 1) as i ON i.parent_id>0 AND pl.invoice_id=i.parent_id AND pl.product_id=i.beneficiary_account
WHERE pl.action=6 AND p.cikkszam = 'S6511415-BLK' AND (pl.stamp BETWEEN '2015-08-15 00:00:00' AND '2015-08-15 23:59:59') AND pl.warehouse_name='Garage - Árkád'
ORDER BY p.cikkszam
The result will be two rows which is OK, but there are no id and vat:
id vat inv_id pl_id qty price name
NULL NULL 93117 21961 -1.00 1096.85 HUF SUPRA ICON SX BLACK DB
NULL NULL 93117 21961 -1.00 1096.85 HUF SUPRA ICON SX BLACK DB
I tried LIMIT 1, GROUP BY, MIN, MAX, etc.
I know that DISTINCT is working with my sample, but it is a simplified query to show you the problem itself.
How can I achieve the result with only two rows, but with a value in the id and vat column, using some technique in (or around) the LEFT JOIN subquery?