【问题标题】:Getting column cannot be null while trying to use 'insert into select' query尝试使用“插入选择”查询时获取列不能为空
【发布时间】:2017-11-05 04:43:37
【问题描述】:

插入表 1 (id,table2id)

values
(
    1,
    (select distinct id from TABLE2 s table2 where table2.data='ABC')

);

假设 TABLE1 的 table2id 列不可为空。但是,(select distinct id from TABLE2 s table2 where table2.data='ABC') 查询可能会返回 null。当 (select distinct id from TABLE2 s table2 where table2.data='ABC') 查询未返回 null 且未收到“table2id 不能为 null”错误消息时,如何将上述查询插入 TABLE1。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    用你想要的任何值替换 0

    insert into TABLE1 (id,table2id)
    values
    (
        1,
        COALESCE((SELECT DISTINCT id FROM TABLE2 as table2 WHERE table2.data = 'ABC'),0))
    );
    

    【讨论】:

    • 使用COALESCEIFNULL 比编写两次查询更好。
    • 使用下面的 COALESCE 对我有用。 INSERT INTO TABLE1 (id, table2id) VALUES (1, COALESCE((SELECT DISTINCT id FROM TABLE2 as table2 WHERE table2.data = 'ABC'),0));谢谢。大家。
    • 感谢两位cmets,我更新了我的答案以包含您的评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 2018-10-07
    相关资源
    最近更新 更多