我可以在触发器中进行查询吗?

Can i have a Query within a Trigger?

我是 SQL 的新手。我可能没有使用正确的术语或语法。该代码背后的目标是,如果一个城市的人口减少超过 10%,那么该城市所在大陆的人口将减少 5%。我试图通过使用嵌套查询使城市人口下降与其大陆之间的 link。这是正确的方法吗?

DELIMITER $$ 
CREATE TRIGGER PopAdjustment 
AFTER UPDATE
ON City 
FOR EACH ROW 
IF (City.NEW_Population / City.Population) =  < .9   
THEN
SELECT City.Name, Country.Continent FROM Country JOIN Country ON  City.CountryCode = Country.Code 
WHERE City.NEW_Population / City.Population  =  < .9 
SET Country.Continent = (Country.Continent * 0.95) ; 
END IF;
END$$
DELIMITER ;

这个触发器在句法和概念上有很多错误。我建议你阅读手册。但为了帮助澄清,请同时研究这个

drop table if exists city,country;
create table city(name varchar(10), population int, countrycode int);
create table country(code int primary key,continent int);
insert into city values('aaa',100,1);
insert into country values(1,100);

drop trigger if exists t;
DELIMITER $$ 
CREATE TRIGGER t 
AFTER UPDATE
ON City 
FOR EACH ROW 
begin
 IF (NEW.Population / old.Population) <= .9   THEN
    update country
        SET Country.Continent = Country.Continent * 0.95 
        where country.code = new.countrycode; 
 END IF;
END $$
DELIMITER ;
update city
    set population = 80
    where city.name = 'aaa';

select * from city;
select * from country;
+------+------------+-------------+
| name | population | countrycode |
+------+------------+-------------+
| aaa  |         80 |           1 |
+------+------------+-------------+
1 row in set (0.001 sec)