使用WHERE子句更新/插入的解决方法

时间:2011-12-06 00:49:20

标签: mysql database

我对此有一个严重的大脑放屁,但基本上我有一张看起来与此类似的表 -

+  id  +  staff_id   +    location       +    date    + dismiss_boolean + 
+------+-------------+-------------------+------------+-----------------+
+   1  +      22     + Bedfordshire      + 2011-11-01 +        0        +
+   2  +      22     + Hertfordshire     + 2011-11-02 +        1        +
+   3  +      16     + Bedfordshire      + 2011-12-01 +        0        +
+   4  +      17     + Bedfordshire      + 2011-11-22 +        0        +
+   5  +      77     + Hertfordshire     + 2011-11-01 +        1        +
+   6  +      77     + Cambridgeshire    + 2011-11-01 +        1        +

我所追求的是(在一次查询中) -

如果该行存在,即:有一行其中staff_id = 6且location = Bedfordshire,则如果日期字段早于 X ,则更新行 日期。

否则,如果该行不存在(没有staff_id = 6且location = Bedfordshire的行),则将数据作为新行插入。

通常你会使用 -

INSERT....ON DUPLICATE KEY UPDATE...

但是如果使用ON DUPLICATE,你不能在UPDATE语句中使用WHERE子句。再次,由于重复,您不能在location和staff_id字段上使用UNIQUE Indexes。

所以我正在查询 -

IF(
(SELECT COUNT(*) FROM `notifications` WHERE `staff_id` = '6' AND `location` = 'Bedfordshire') > 0
, UPDATE `notifications` SET `dismiss_boolean` = '1', `date` = '2011-12-10'  WHERE `staff_id` = '6' AND `location` = 'Bedfordshire' AND `date` < '2011-12-10' 
, INSERT INTO `notifications` (`staff_id`, `location`, `date`, `dismiss_boolean`) VALUES ('6', 'Bedfordshire', '2011-12-10', '1')
)

但是这会引发语法错误,并且从我记忆中错误地使用IF函数。

所以有人有任何想法我怎么能做到这一点?我能想到的唯一解决方案是在更新或插入数据之前查询表,但如上所述,理想情况下我想在单个查询中执行此操作。

任何帮助都会受到赞赏,因为我在一天的大部分时间里一直在解决这个问题,而且我还没有找到搜索Google / Stackoverflow的王牌。

1 个答案:

答案 0 :(得分:1)

我不确定这是否仍然存在,但仅供参考:

INSERT INTO notifications
    (staff_id, location, `date`, dismiss_boolean
VALUES ('6', 'Bedfordshire', '2011-12-10', '1')
ON DUPLICATE KEY UPDATE
    dismiss_boolean = if(VALUES(`date`) < '2011-12-10',
                         VALUES(dismiss_boolean),
                         dismiss_boolean),
    `date` =          if(VALUES(`date`) < '2011-12-10',
                         VALUES(`date`),
                         `date`);
相关问题