2012-10-30 44 views
2

我有一個TBL,例如:MYSQL插入第一個空列

uniqueId  | col1 | col2 | col3 
u1     8  
u2 
u3     13   89 

我要的是插入到第一個空列(可以讓他們空是否有幫助)。在給定的,如果我將添加到u1值2它將被插入到col2。如果我爲u2做它,它將進入col1。對於U3它將進入U3。這三個查詢將做的伎倆,但我寧願做一個。

INSERT INTO tbl SET col1 = $toInsertVal WHERE uniqueId=u col1=''
INSERT INTO tbl SET col2 = $toInsertVal WHERE uniqueId=u col1<>'' AND col2=''
INSERT INTO tbl SET col3 = $toInsertVal WHERE uniqueId=u col1<>'' AND col2<>'' AND col3=''

回答

1
insert into tbl set 
col1 = case when col1 = '' then $toInsertVal else col1 end 
, col2 = case when col2 = '' and col1 <> '' then $toInsertVal else col2 end 
... 
where uniqueid = u 

我忽略NULL S表示簡單起見。基本上,您可以在每列上使用CASE,如果不需要更改,請檢查第一個空列並將其值設置爲當前值。

+0

是否可以插入行的新值,而不必指定列名稱?即查詢不能查看該行的哪一列是空的並用新值填充它? – Dante