I have this query:
INSERT INTO tab_reminder (ID_cliente, ID_articolo, Data_acquisto)
SELECT c.ID_cliente as cliente, ca.ID_articolo as articolo, MAX(c.Data_contratto) as ultimoAcquisto
FROM tab_contratti_articoli ca
LEFT JOIN tab_contratti c ON c.ID_contratto = ca.ID_contratto
LEFT JOIN tab_articoli a ON ca.ID_articolo = a.ID_articolo
LEFT JOIN tab_clienti cl ON c.ID_cliente = cl.ID_cliente
WHERE c.ID_cliente != 0
AND cl.ID_utente = 0
AND Giorni_reminder != 0
AND c.Data_contratto <= DATE_SUB('2017-05-16', INTERVAL Giorni_reminder DAY)
AND c.Data_contratto > DATE_SUB(DATE_SUB('2017-05-16', INTERVAL Giorni_reminder DAY), INTERVAL 60 DAY)
AND (c.Data_contratto NOT BETWEEN DATE_SUB('2017-05-16', INTERVAL Giorni_reminder DAY) AND '2017-05-16')
GROUP BY c.ID_cliente, ca.ID_articolo
ON DUPLICATE KEY UPDATE ID_cliente=ID_cliente, ID_articolo=ID_articolo, Data_acquisto=Data_acquisto, Articolo_visibile=Articolo_visibile;
Basically, it annoys me that I have to repeat DATE_SUB(DATE_SUB('2017-05-16', INTERVAL Giorni_reminder DAY)
date result.
Is there a way to declare a variable in MySQL for that date?
Something like:
SET @newDate := DATE_SUB(DATE_SUB('2017-05-16', INTERVAL Giorni_reminder DAY);
And then use it like this:
AND c.Data_contratto <= @newDate
AND c.Data_contratto > DATE_SUB(@newDate, INTERVAL 60 DAY)
AND (c.Data_contratto NOT BETWEEN @newDate AND '2017-05-16')
I have searched and for what I have found, there is no way or it's not allowed to declare variables or aliases in the WHERE
clause, but maybe there is a workaround to avoid typing the same thing several times in the same query.
As always, thank you all and have a nice day!
Update 1:
I have seen @TimBiegeleisen's link and I find it very, very interesting. But the project I work in uses deprecated mysql API to query. See example:
$sqlExample = "SELECT * FROM tab_example";
$qExample = mysql_query($sqlExample) or die ("Error in $sqlExample: ".mysql_error());
$rsExample = mysql_fetch_object($qExample);
Taking this into consideration, are still Prepared statements viable?
Returning to OP, Is it a way of declaring the variable in the query where I need it (In WHERE
clause)?
Update 2:
This is a clarification of why this: How to declare a variable in MySQL?
Is not working for me or I am not managing to make it work.
I don't have to declare static data, I would like to declare a variable that is result of a SELECT.
The data I want to store and keep using within the WHERE
clause is this DATE_SUB('2017-05-16', INTERVAL Giorni_reminder DAY)
, I removed the PHP variable because I recall can create confusion.
Is just that Giorni_reminder
is a result of the SELECT and I want to use it in WHERE clause. If you see the query, I am repeating the same thing several times.
I wanted to avoid that.
So, something like this doesn't work for me:
SET @start = 1, @finish = 10;
I need something like posted in OP. If it's possible.
If it's not possible, then I have learned a lesson! :D