2

我有一个 tbl,例如:

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

我想要的是插入第一个空列(如果有帮助可以使它们为空)。在给定的情况下,如果我将值 2 添加到 u1,它将被插入 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=''

4

1 回答 1

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在每一列上使用 a,检查第一个空列并将其值设置为当前值(如果不需要更改)。

于 2012-10-30T14:36:03.567 回答