2014-02-28 93 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 
    )