我有一个如下所示的SQL查询:
DELETE
price.*
FROM
price
JOIN
service
ON
price.service_id = service.id
WHERE
price.country_from_id NOT IN
(SELECT
country_id
FROM
carrier_zone_country
JOIN
carrier_zone
ON
carrier_zone_id = carrier_zone.id
WHERE
carrier_zone.carrier_service_id = service.carrier_service_id)
OR
price.country_to_id NOT IN
(SELECT
country_id
FROM
carrier_zone_country
JOIN
carrier_zone
ON
carrier_zone_id = carrier_zone.id
WHERE
carrier_zone.carrier_service_id = service.carrier_service_id)
我希望通过将子查询移动到FROM
子句并为其命名来避免两次运行子查询。但是,这给了我语法错误。查看文档,我可以看到只有SELECT FROM
子句可以在其中包含一个命名子查询。
首先,我想知道为什么会这样?其次,我怎样才能重新编写这个SQL查询以避免两次执行相同的子查询。
答案 0 :(得分:1)
执行一个NOT EXISTS
子查询,其中检查国家/地区和来自国家/地区:
DELETE
price.*
FROM
price
JOIN
service
ON
price.service_id = service.id
WHERE
NOT EXIST(SELECT
1
FROM
carrier_zone_country
JOIN
carrier_zone
ON
carrier_zone_id = carrier_zone.id
WHERE country_id IN (price.country_from_id, price.country_to_id)
AND carrier_zone.carrier_service_id = service.carrier_service_id))