Database manager system: MySql 5.7.11
I'm trying to create a SQL query to delete all the records that meet the following condition:
This is a tariff system, a tariff table is related to the price table in a one-to-many relationship, and each price is related to a product.
Because tariffs are created through batch actions, sometimes in a tariff, several prices are recorded for the same product. My intention is to keep in each tariff only the last price (the highest id) for each product and eliminate the previous prices, for this I am using the following query:
DELETE p
FROM ges_precio as p
WHERE p.tarifa_id = :tarifa
and id <
(select max(a.id) as id
from ges_precio a
where a.tarifa_id = :tarifa
and p.producto_id = a.producto_id
)
But I'm getting the following error:
You can not specify target table 'p' for update in FROM clause
I have tried to encapsulate the subquery in another select and use an alias to solve it as explained here but it does not work either.
I'm looking for a way to do the query, without using a subquery in the FROM
that consults the price table.
UPDATE:
I will give an example so that I understand better what I intend to do, this is the table ges_precio:
id | amount | rate_id | product_id
1 | 24 | 1 | 24
2 | 16 | 1 | 53
3 | 18 | 1 | 24
Right now tariff 1 consists of three prices, the problem is that two of them refer to the same product 24, in this case I want to discard the oldest price for this rate and product 24, that is to say after using the query the table should look like this:
id | amount | rate_id | product_id
2 | 16 | 1 | 53
3 | 18 | 1 | 24