【问题标题】:Can i have a Query within a Trigger?我可以在触发器中进行查询吗?
【发布时间】:2020-08-16 05:55:31
【问题描述】:

我是 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 ;

【问题讨论】:

  • 不允许从触发器返回结果集(即选择而不是选择进入)
  • 您在 2 天前问过这个问题。如果您添加示例数据和预期输出,您将更有可能获得答案。

标签: mysql sql triggers database-trigger


【解决方案1】:

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

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)

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多