2015-07-10 44 views
2

我有一個填充10k行數據的數據庫表。大部分這些行在特定列中都有空值。如何將這個空值替換爲例如字符串列的空字符串?如何從表格列中刪除空值?

我在尋找的最簡單辦法做到這一點,因爲這個操作只需要進行一次

我曾嘗試:

UPDATE tablename set mycolumn='' where mycolumn is null; 

這給了我下面的錯誤:

Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.

我不是數據庫管理員,所以我不能禁用安全模式。

UPDATE tablename set mycolumn='' 
    where Id in (SELECT Id FROM tablename where mycolumn is null); 

這給了我下面的錯誤:

Error Code: 1093. You can't specify target table 'tablename' for update in FROM clause.


注:

在上面的例子中我已經取代了真正的表名和字段名佔位符。

+0

[使用列級別WHERE子句更新多個列中的所有SQL NULL值?](http://stackoverflow.com/questions/3938958/update-all-sql-null-values-in-multiple-columns -using-column-level-where-clause) –

+0

做相反的事情,用NULL替換空字符串! – jarlh

+1

是的,要求很奇怪。爲什麼你想用空白的字符替換NULL值? –

回答

1

你可以嘗試

UPDATE tablename set mycolumn = '' 
where Id IN (select Id from (select Id from tablename where mycolumn IS NULL) as x) 

但是爲什麼你要在所有的空字符串替換NULL值?

如果您可以禁用安全模式this將是重複的。

+0

這對我有用。替換null的原因是測試。 –

+0

@ transporter_room_3:so [Andy's approach](http://stackoverflow.com/a/31335447/284240)沒有用?我很好奇,我主要使用sql-server,所以我無法測試它。 –

+1

不,我得到這個錯誤:(錯誤代碼:1175.您正在使用安全更新模式,並且您嘗試更新沒有使用KEY列的WHERE表),這是相同的。 –

0

您可以更改表格併爲列設置NOT NULL。

而且你也可以簡單地做到以下幾點:

To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.

+0

如果列中已經包含「null」值,那麼這將不起作用。它違反了約束條件,數據將根據該方案無效,因此您應該先更新,然後設置約束條件。 –

+0

通過改變表格將默認值設置爲''並且在表格中定義爲非空值,它肯定會起作用 –

+0

好吧,但那不是你的答案。 –

0

好了,你可以不喜歡它:

UPDATE tablename set mycolumn='' where mycolumn is null and Id is not null; 

這實際上並不改變更新邏輯東西(因爲ID是主鍵並且不能爲空),並使用where子句中的鍵列。