2012-01-24 28 views
1

我想寫很奇怪的查詢,我有if聲明的問題,所以我有我的表中的2個字段deleted_1deleted_2我想更新,所以這個如何我認爲應該是:如果價值不存在的Mysql更新

Update `messages` 
    if(`deleted_1` == null) SET `deleted_1` = 1 
    else 
    if(`deleted_2` == null) SET `deleted_2 = 1 
    ---and here goes some simple WHERE statements 

但是,這並不工作,所以basicly我想檢查是否a字段爲空,然後更新它,如果不檢查b字段,如果它是空的更新b場,現在我不知道,也許有可能以更簡單的方式做到這一點,我很迷茫:)

+0

如果值不存在,則Mysql更新或Mysql INSERT如果值不存在? – Sarfraz

+0

不,我需要更新 – Linas

回答

3
UPDATE MyTable 
SET deleted_2 = CASE WHEN ISNULL(deleted_1, '') == '' OR ISNULL(deleted_2, '') != '' THEN deleted_2 ELSE 1 END, 
    deleted_1 = CASE WHEN ISNULL(deleted_1, '') != '' THEN deleted_1 ELSE 1 END 

這是說:

deleted_1: will be update if (deleted_1 == null) 
deleted_2: will be updated if (deleted_1 != null && deleted_2 == null), 
      This is to match your if else condition 
+0

嗯查詢沒有錯誤,但它不會更新任何字段,即使這兩個字段都爲空或只有其中一個爲空 – Linas

+0

@Linas我更新了查詢以說明空('')之前它只會在值爲NULL時才起作用 –

1

我覺得你的問題是,空= NULL。表達式deleted_2 == null將永遠不會解析爲真。首先,單=,不是雙(至少在MySQL),其次,嘗試這些:

mysql> select false = null; 
+--------------+ 
| false = null | 
+--------------+ 
|   NULL | 
+--------------+ 
1 row in set (0.00 sec) 

mysql> select true = null; 
+-------------+ 
| true = null | 
+-------------+ 
|  NULL | 
+-------------+ 
1 row in set (0.00 sec) 

mysql> select null != null; 
+--------------+ 
| null != null | 
+--------------+ 
|   NULL | 
+--------------+ 
1 row in set (0.01 sec) 

mysql> select null = null; 
+-------------+ 
| null = null | 
+-------------+ 
|  NULL | 
+-------------+ 
1 row in set (0.00 sec) 

你的表達式需要或者是「其中TABLE.COLUMN爲空」,「哪裏TABLE.COLUMN不爲空「或ifnull()的一些變體:https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull