【问题标题】:MYSQL: How can insert into a table a variable, depending on the variable if its not null?MYSQL:如何将变量插入表中,这取决于变量是否为空?
【发布时间】:2021-06-15 20:52:44
【问题描述】:

我的示例代码:

SET @VARIABLE1 := 'Heyho';
create table Test(id integer, title varchar(100));
insert into Test(id, title) values(1, "Hello");
insert into Test(id, title) values(2, (SELECT @VARIABLE1));
insert into Test(id, title) values(3, (SELECT @VARIABLE2 WHERE @VARIABLE2 IS NOT NULL));
select * from Test;

我的实际结果:

id  title
1   Hello
2   Heyho
3   NULL

我的预期结果:

id  title
1   Hello
2   Heyho

如果@VARIABLE2 不为空,我只想插入 ID 为 3 的行

【问题讨论】:

  • insert into Test(id, title) SELECT 3, @VARIABLE2 WHERE @VARIABLE2 IS NOT NULL; dbfiddle.uk/…
  • @Akina 非常感谢!现在可以了!

标签: mysql variables null insert


【解决方案1】:

由于 Akina 的评论,正确的代码是:

SET @VARIABLE1 := 'Heyho';
create table Test(id integer, title varchar(100));
insert into Test(id, title) values(1, "Hello");
insert into Test(id, title) SELECT 2, @VARIABLE1 WHERE @VARIABLE1 IS NOT NULL;
insert into Test(id, title) SELECT 3, @VARIABLE2 WHERE @VARIABLE2 IS NOT NULL;
select * from Test;

现在可以了,我得到了预期的结果!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2018-01-17
    相关资源
    最近更新 更多