mysql - 触发器从源表和另一个表插入数据

标签 mysql variables triggers

我正在使用 mysql 5.5,我正在尝试定义一个触发器。

这是我的表格。

+------Table1------+ SOURCE: The one which pulls the trigger
+ id | post_title  +
+------------------+
+ 1  | title1      +
+ 2  | title2      +
+------------------+
+------Table2-------+ Where I need to get the information. 
+ id  | nicename    + Note: Table1.post_title = Table2.nicename
+-------------------+
+ 99  | title1      +
+ 86  | title2      +
+-------------------+
+----------Table3---------------+ DESTINATION: Where I need to insert
+ id  | meta_key  | meta_value  + Note: Table1.id = Table3.meta_value
+-------------------------------+       Table2.id= Table3.id
+ 99  | hub_page  |        1    +
+ 86  | hub_page  |        2    +
+-------------------------------+

This is the query I wrote but it returns: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 6

DELIMITER $$
CREATE TRIGGER 'trigger_name' AFTER INSERT ON 
'table1' FOR EACH ROW 
BEGIN
    DECLARE user_id int;
    SELECT id into user_id from table2 where(table2.nicename = new.post_title);
    INSERT INTO table3(id,metakey,metavalue) VALUES(user_id,'hub_page',new.id);
END$$;

最佳答案

根据您的触发器定义,它说在 table3 上插入后运行它,但在您的问题中,您似乎需要在表 1 上插入后运行它,对 table1 的评论拉动触发器的那个 所以我假设当插入发生在表 1 上时,您需要在表 3 中插入​​一行,而在触发器中,您需要从表 2 中获取数据,为此您可以将触发器重写为

CREATE TRIGGER new_table1_trigger
AFTER INSERT ON 
`Table1` FOR EACH ROW 
INSERT INTO table3(id,meta_key,meta_value) VALUES(
  (SELECT id  from table2 where table2.nicename = new.post_title LIMIT 1),
  'hub_page',
  new.id);  

在下面的演示中,您会注意到我对 table3 使用了任何独立插入,所有插入都是由触发器完成的

Demo

Note you are using trigger for insert only so it will only work for inserts,but if you update the data of table1 then table3 will not be updated for this you will need an update trigger too

Also don't use single quotes for table/column names instead use back-ticks to escape reserved keywords

关于mysql - 触发器从源表和另一个表插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24024211/

相关文章:

mysql - 触发器错误(mysql)

mysql - MySQL 中的 Kannel DLR 报告

php - 用于删除具有重复条目的行的 MySQL 查询

php - 更新正在运行的查询但不更新表 php

javascript - 如何使用我的数据库中的纬度和经度值在谷歌地图上显示?

python - 如果 x 相同,如何不打印?

mysql - 如何更改MySQL表触发器中的auto_increment字段?

c++ - 使用基于数组和范围的 For 循环替换一些基本代码行

session - 在 Lift Scala 中存储 session 变量

postgresql - 为使用批量插入的表使用插入时触发更新旧记录