gpt4 book ai didi

MYSQL - 如果表为空则插入

转载 作者:行者123 更新时间:2023-11-29 02:41:54 27 4
gpt4 key购买 nike

如果表为空(0 行),我想在表中插入一些数据。

我试过这个:

IF NOT EXISTS(SELECT 1 FROM `account_types`)
THEN
INSERT INTO `account_types` (`type`, `group`) VALUES ('400', 'test');
INSERT INTO `account_types` (`type`, `group`) VALUES ('401', 'test2');
END IF;

但是我明白了

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS(SELECT 1 FROM account_types) THEN INSERT INTO `account_types' at line 1

我能做什么?我正在使用 MYSQL

最佳答案

INSERT INTO `account_types`(`type`, `group`)
SELECT * FROM
(SELECT '400' `type`, 'test' `group` UNION ALL
SELECT '401' `type`, 'test2' `group` UNION ALL
SELECT '402' `type`, 'test3' `group`) A
WHERE NOT EXISTS (SELECT NULL FROM account_types B WHERE A.type=B.type);

演示

http://sqlfiddle.com/#!9/d1e80e/1

关于MYSQL - 如果表为空则插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49941928/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com