Postgresql在UPDATE请求中添加WHERE子句

时间:2016-12-08 11:55:18

标签: sql postgresql

我打算写一个SQL请求UPDATE,我想验证table2.fld5是否已包含' Hello'为了不多次写,但没有找到实现此验证的方法。

请求是:

UPDATE table2
    SET fld5 = concat(fld5, 'Hello')
    WHERE NOT EXISTS (SELECT *
                      FROM table1
                      WHERE table1.fld1 = table2.fld1 AND
                            table1.fld2 = table2.fld2 AND
                            table1.fld3 = table2.fld3
                     )
     AND table2.fld4 > (NOW() - INTERVAL '79 MINUTE');

2 个答案:

答案 0 :(得分:1)

如何将条件添加到where

UPDATE table2
    SET fld5 = concat(fld5, 'Hello')
    WHERE (fld5 not like '%Hello' OR fld5 IS NULL) AND  -- perhaps this should be '%Hello%'
          NOT EXISTS (SELECT *
                      FROM table1
                      WHERE table1.fld1 = table2.fld1 AND
                            table1.fld2 = table2.fld2 AND
                            table1.fld3 = table2.fld3 AND
                            table2.fld4 > (NOW() - INTERVAL '79 MINUTE')
                     ); 

我同意有关fld4比较的评论。我认为这是逻辑:

UPDATE table2
    SET fld5 = concat(fld5, 'Hello')
    WHERE (table2.fld5 not like '%Hello' OR table2.fld5 IS NULL) AND  -- perhaps this should be '%Hello%' AND
          table2.fld4 > (NOW() - INTERVAL '79 MINUTE') AND  -- or should this be <
          NOT EXISTS (SELECT *
                      FROM table1
                      WHERE table1.fld1 = table2.fld1 AND
                            table1.fld2 = table2.fld2 AND
                            table1.fld3 = table2.fld3                                
                     ); 

答案 1 :(得分:1)

也许您的日期检查需要在exists子查询之外:

UPDATE table2 SET fld5 = concat(fld5, 'Hello') 
WHERE fld5 NOT LIKE '%Hello%' AND table2.fld4 > (NOW() - INTERVAL '79 MINUTE'
AND NOT EXISTS (SELECT * FROM table1 WHERE table1.fld1 = table2.fld1 AND table1.fld2 = table2.fld2 AND table1.fld3 = table2.fld3))

相关问题