如果存在则每次出现更新+1

时间:2017-10-11 22:53:47

标签: sql

我目前有,并且当我遇到与该ID相关的不良体验时,我正在尝试显示名字和姓氏。如果存在糟糕的经历,我想在我的专栏“罢工”中加1,我现在非常坚持。

SELECT first, last FROM staff JOIN comments 
ON staff.id = comments.staff_id AND exp = 'bad' 
AND IF EXISTS exp = 'bad'
UPDATE comments
SET strikes = +1
WHERE exp = 'Bad';

3 个答案:

答案 0 :(得分:0)

我不理解你的桌子,但是这样的事情怎么样:

UPDATE comments
SET strikes = strikes + 1
WHERE exp = 'Bad';

答案 1 :(得分:0)

这不是IF EXISTS的使用方式。看一下这个StackOverflow thread

IF EXISTS查看子查询的结果,以检查是否返回任何内容。因此,您应该将查询更改为:

create procedure select_or_insert()
begin
   IF EXISTS (
              SELECT first, last 
              FROM staff JOIN comments 
              ON staff.id = comments.staff_id AND exp = 'bad'
   )
   UPDATE comments
   SET strikes = +1
   WHERE exp = 'Bad';
end $$

答案 2 :(得分:0)

据我所知,你有一张桌子工作人员。如果id的exp为bad,则需要更新comments表中的strikes,因为没有该id的错误体验。

Update comments as c
   INNER JOIN (SELECT id, count(*) As badexp_cnt
                    FROM staff
                  where exp = 'bad'
                  group by id) s
    ON s.id = c.staff_id
SET strikes = badexp_cnt

- 你需要罢工+ badexp_cnt还是只需要badexp_count?每次更新时,Strike + badexp_count都会增加警示值