我是SQL的新手,我可能没有使用正确的术语或语法。我可能没有使用正确的术语或语法。 代码背后的目标是,如果一个城市的人口减少了10%以上,那么这个城市的大陆人口就会减少5%。 我试图通过使用嵌套查询将一个城市的人口下降与其大陆联系起来。 这样做对吗?
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)