This is part of a (very) bigger query.
The error is the missing alias "clienti_con_rinnovo" (Table "clienti_con_rinnovo" does not exists). I don't need to rewrite the query (the logic is right) but probably an help to get that aliases.
If interesting (but you know yet) the order is LEFT JOIN
and following the UNION
.
Thank you in advance
SELECT * FROM
( SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE
renew IS NOT NULL
GROUP BY id ) AS clienti_con_rinnovo
UNION
SELECT * FROM
( SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE renew IS NULL
GROUP BY id ) AS clienti_senza_rinnovo
LEFT JOIN clienti_con_rinnovo ON clienti_con_rinnovo.id = clienti_senza_rinnovo.id
WHERE clienti_con_rinnovo.id IS NULL
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `clienti_con_rinnovo` ADD INDEX `clienti_rinnovo_idx_id` (`id`);
ALTER TABLE `transactions` ADD INDEX `transactions_idx_renew_id` (`renew`,`id`);
ALTER TABLE `transactions` ADD INDEX `transactions_idx_id_datetransaction` (`id`,`dateTransaction`);
SELECT
*
FROM
(SELECT
transactions.id,
MAX(transactions.dateTransaction) AS last_transaction_renew
FROM
transactions
WHERE
transactions.renew IS NOT NULL
GROUP BY
transactions.id
ORDER BY
NULL) AS clienti_con_rinnovo
UNION
SELECT
*
FROM
(SELECT
transactions.id,
MAX(transactions.dateTransaction) AS last_transaction_renew
FROM
transactions
WHERE
transactions.renew IS NULL
GROUP BY
transactions.id
ORDER BY
NULL) AS clienti_senza_rinnovo
LEFT JOIN
clienti_con_rinnovo
ON clienti_con_rinnovo.id = clienti_senza_rinnovo.id
WHERE
clienti_con_rinnovo.id IS NULL