选择Count Row然后更新值

时间:2014-02-28 07:15:15

标签: mysql sql

只需要一些想法

有没有办法可以选择计数然后更新它的值?

这是我要编辑的代码。

我在表message

中收到了新邮件的数量
select count(id) as new from message where owner_id = '1' and status = '1' and isRecieve = '0'

当我收到消息的数量时,我希望它将messageselect查询中获取的所有内容设置为isRecieve = 1

有一种方法,一旦我查询我更新所有isRecieve为1?

 select count(id) as new from message where owner_id = '1' and status = '1' and isRecieve = '0' then update isRecieve = 1

感谢。

2 个答案:

答案 0 :(得分:1)

您不应该为您的案例选择COUNT。事实上,你想要达到的目标是:

  • 更新相应记录
  • 发现,触摸了多少行

这可以通过以下方式解决:

UPDATE 
  message 
SET 
  isReceive = '1' 
WHERE 
  owner_id = '1' 
  AND 
  status = '1' 
  AND 
  isRecieve = '0'

然后要么

SELECT ROW_COUNT()

在SQL中检索受影响的行,或在应用程序中执行类似mysqli_affected_rows()的操作(函数在PHP中,但在任何语言的任何mysql连接驱动程序中都可以使用相同的东西)。

答案 1 :(得分:0)

UPDATE message set 
    isRecieve = 1 where 
    owner_id = '1' and 
    status = '1' and 
    isRecieve = '0' and 
    exists (
        select 1 from message where 
            owner_id = '1' and 
            status = '1' and 
            isRecieve = '0'
            group by id having count(*) = 1
    )