SQL Trigger,如果不存在则添加新字符串

时间:2014-07-16 12:57:10

标签: sql wordpress triggers

我有一张桌子wp_postmeta

meta_id     bigint(20)   unsigned            PRI     (NULL)   auto_increment           
post_id     bigint(20)   unsigned            MUL     0                                 
meta_key    varchar(255) utf8_unicode_ci     MUL     (NULL)                             
meta_value  longtext     utf8_unicode_ci             (NULL) 
表格如下:

meta_id     post_id       meta_key   meta_value
1           1             area       12
2           1             rooms      2
3           2             rooms      3

我需要创建一个触发器,如果​​不存在,将在该表中添加一个字符串 meta_key ='area'和meta_value ='0'。 或UPDATE,其中meta_key ='area'和meta_value ='NULL'。

但是... 每个post_id可能有很多meta_key。每个post_id的meta_key ='area'设置为限制1。 但问题是并非每个post_id都有meta_key ='area' 所以首先需要创建它!!

我现在有这样的东西......(下面的代码)它是meta_key ='0'的meta_value ='0'的一部分。但我不明白如果不是这样我必须创建这个字符串存在。

CREATE
    TRIGGER `trigger` BEFORE INSERT ON `wp_postmeta` 
    FOR EACH ROW BEGIN
    IF NEW.meta_key = 'area' AND NEW.meta_value IS NULL THEN
    SET NEW.meta_value = '0';
END IF;
END;
$$

2 个答案:

答案 0 :(得分:0)

由于看起来必须在wp_posts条目之前创建wp_postmeta条目(否则您将不知道post_id),我会在wp_posts上放置一个后插入触发器{1}}插入wp_postmeta行。

答案 1 :(得分:0)

那样做了:

DELIMITER $$

USE `dev_hiponia_hipo`$$

DROP TRIGGER IF EXISTS `area_for_id`$$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    TRIGGER `dev_hiponia_hipo`.`area_for_id` AFTER INSERT ON `wp_posts`
    FOR EACH ROW BEGIN
    IF NEW.post_type = 'property' THEN
        INSERT INTO wp_postmeta (meta_key, meta_value, post_id) VALUES ('area', '0', NEW.ID);
    END IF;
    END;
$$

DELIMITER ;

- >当我设置新帖子时,它会自动设置区域值=> ' 0'

我为wp_postmeta设置的第二个触发器:

      DELIMITER $$

USE `dev_hiponia_hipo`$$

DROP TRIGGER IF EXISTS `areamodif`$$

CREATE
    /*!50017 DEFINER = 'devhiponia'@'192.168.1.%' */
    TRIGGER `areamodif` AFTER UPDATE ON `wp_postmeta` 
    FOR EACH ROW BEGIN
    IF NEW.meta_key = 'area' AND NEW.meta_value = '' THEN
        UPDATE wp_postmeta
        SET  meta_value = '0' 
        WHERE NEW.meta_key = 'area' AND meta_value = '';
    END IF;
END;
$$

DELIMITER ;




DELIMITER $$

USE `dev_hiponia_hipo`$$

DROP TRIGGER IF EXISTS `areaifdelete`$$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    TRIGGER `areaifdelete` AFTER DELETE ON `wp_postmeta`
    FOR EACH ROW BEGIN
    IF OLD.meta_key = 'area' THEN
        INSERT INTO wp_postmeta (meta_key, meta_value, post_id) VALUES ('area', '0', OLD.post_id);
    END IF;
    END;
$$

DELIMITER ;