2012-10-30 45 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