MySQL不要INSERT如果NULL字段

时间:2015-02-08 21:48:20

标签: mysql

如果inventory.nickNULL? INSERT INTO gold_log (nick, amount, stream_online, modification_type, dt) SELECT inventory.nick, SUM(inventory.stat_2*.01), False, 12, NOW() FROM inventory INNER JOIN equipment_shoes ON inventory.id=equipment_shoes.id AND inventory.item=8 INNER JOIN gold_log ON inventory.nick=gold_log.nick AND gold_log.dt > FROM_UNIXTIME(1423421534.32); ,我怎么能不为以下声明做任何INSERT?提前谢谢你!

{{1}}

2 个答案:

答案 0 :(得分:1)

在where子句中添加该条件?

INSERT INTO gold_log (nick, amount, stream_online, modification_type, dt) 
    SELECT inventory.nick, SUM(inventory.stat_2*.01), False, 12, NOW()
    FROM inventory
        INNER JOIN equipment_shoes ON
        inventory.id=equipment_shoes.id
        AND inventory.item=8
        INNER JOIN gold_log ON 
        inventory.nick=gold_log.nick
        AND gold_log.dt > FROM_UNIXTIME(1423421534.32);
    HAVING
        inventory.nick IS NOT NULL

(由WHERE引起的隐式分组)将HAVING更改为SUM

此外,您可以使列本身不可为空:

ALTER TABLE inventory MODIFY COLUMN nick VARCHAR(200) NOT NULL;

但仅凭这一点无法解决问题。如果列不可为空,并且列具有默认值,则如果查询中nick为空,则所有新行都将获得此默认值。如果它没有默认值,则插入将完全失败,包括那些填充了nick的行。因此对insert语句本身的更改是最重要的:它将跳过那些没有nick的行。

答案 1 :(得分:0)

只需添加IS NOT NULL条件:

INSERT INTO gold_log (nick, amount, stream_online, modification_type, dt) 
    SELECT inventory.nick, SUM(inventory.stat_2*.01), False, 12, NOW()
    FROM inventory
        INNER JOIN equipment_shoes ON
        inventory.id=equipment_shoes.id
        AND inventory.item=8
        INNER JOIN gold_log ON 
        inventory.nick=gold_log.nick
        AND gold_log.dt > FROM_UNIXTIME(1423421534.32)
        WHERE inventory.nick IS NOT NULL;