【问题标题】:MYSQL - insert into and a null value, how to avoid?MYSQL - 插入一个空值,如何避免?
【发布时间】:2012-05-07 09:03:31
【问题描述】:

我有一个 SQL 查询,它看起来像这样:

insert into tableA(order_id, contractnotenumber, shipmentdate, comment) 
    values ((select entity_id from tableb where increment_id = '12345678'), 
    '', '1970-01-01', '');

现在,如果子查询 ((select entity_id from tableb where increment_id = '12345678')) 返回 null,则插入不起作用。我想要的是一种简单的方法,即如果子查询返回 null,则不做任何事情。我尝试插入忽略,但这会插入 0 而不是 null 的行,这有效,但它不是我想要的。在 SQL Server 中,我使用了 if not exists(select...),但这不适用于 MYSQL。

想法?

谢谢!

【问题讨论】:

    标签: mysql insert exists


    【解决方案1】:
    insert into tableA(order_id, contractnotenumber, shipmentdate, comment)
    select entity_id, '', '1970-01-01', '' from tableb where increment_id = '12345678'
    

    如果在tableb 中找不到该行,则不会插入任何内容

    【讨论】:

    • 嗯,不知何故,查询永远运行...缺少一些细节?虽然选择本身会返回数据。
    • @EOB:在此查询中 INSERT 插入 SELECT 选择的内容。如果它什么也没返回 - 然后立即插入“退出”
    • 是的,出口有效,但如果存在某些东西,它会运行并运行,直到我取消它或直到我超时。
    • 啊,我的错,我之前的尝试运行了一些其他事务,它阻止了新查询! 解决了!
    【解决方案2】:

    你也可以试试mysql>插入忽略

    【讨论】:

    • 正如我所说,这在我的情况下不起作用,它会插入 0 为 id 的行,这不是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    相关资源
    最近更新 更多