我想在INSERT
上创建一个MySQL触发器:当在wp_posts
表中插入新记录时,我想更新wp_posts.post_author
从其他两个表中检索数据,使用两个子查询(我想这可以做得更好)。
无论如何,更新应该是"条件",即只有当wp_posts.post_title
值为" A"," B&#34时才必须更新行;或" C"。这可能吗?
这就是我的尝试:
CREATE TRIGGER updatePostIDonInsert
AFTER INSERT
ON wp_posts FOR EACH ROW
BEGIN
-- variable declarations
-- trigger code
// ? (pseudo: if wp_posts.post_title IN ("A","B","C") then...)
UPDATE wp_posts SET post_author =
(SELECT ID from wp_users WHERE user_email =
(SELECT meta_value FROM `wp_postmeta` WHERE post_id = wp_posts.ID AND meta_key = "_from_email"))
END;
感谢任何帮助
[更新]我尝试的最新查询:
CREATE TRIGGER updatePostIDonInsert
BEFORE INSERT
ON wp_posts FOR EACH ROW
BEGIN
IF FIND_IN_SET(NEW.post_title,'General contact,Website contact,Master contact') > 0 AND NEW.post_type ='inbound_com' THEN
SET NEW.post_author = (SELECT ID from wp_users WHERE user_email = (SELECT meta_value FROM wp_postmeta WHERE post_id = NEW.ID AND meta_key = '_from_email'));
END IF;
END;
(如果通过PhpMyAdmin触发部分插入,但没有最终的END并从IF开始,则此方法有效)
答案 0 :(得分:1)
像这样的东西。而不是触发AFTER INSERT利用BEFORE INSERT TRIGGER
CREATE TRIGGER updatePostIDonInsert
BEFORE INSERT
ON wp_posts FOR EACH ROW
BEGIN
// add this condition
IF FIND_IN_SET(NEW.post_title,'A,B,C') > 0 THEN
-- variable declarations
-- trigger code
SET NEW.post_author = (SELECT ID from wp_users WHERE user_email =
(SELECT meta_value FROM `wp_postmeta` WHERE post_id = NEW.ID AND meta_key = "_from_email") LIMIT 1);
END IF;
END;
您需要确保在子查询中只返回一行。我不熟悉您的数据库结构,因此我无法真正告诉您如何优化post_author的子查询。
剩下的由你决定。您可以随时使用FIND_IN_SET。
答案 1 :(得分:0)
这是你需要的吗?
此处触发器只会在新插入的post_title(“A”,“B”,“C”)中执行某些操作
CREATE TRIGGER updatePostIDonInsert
AFTER INSERT
ON wp_posts FOR EACH ROW
BEGIN
// add this condition
IF (NEW.post_title IN ("A","B","C")) THEN
-- variable declarations
-- trigger code
// ? (pseudo: if wp_posts.post_title IN ("A","B","C") then...)
UPDATE wp_posts SET post_author =
(SELECT ID from wp_users WHERE user_email =
(SELECT meta_value FROM `wp_postmeta` WHERE post_id = wp_posts.ID AND meta_key = "_from_email"))
END IF;
END;