2014-02-28 57 views
1

只是需要一些想法选择Count行然后更新值

有没有一种方法可以让我选择计数,然后更新它的价值呢?

这是我的代码进行编辑。

我得到我的表中的新邮件的数量message

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

当我得到消息的数量,我希望它设置所有message得到了select查询isRecieve = 1

有没有办法,一旦我查询我updte所有isRecieve 1?

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

感谢。

回答

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连接驱动程序都可以使用该函数)。

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 
    )