如果表为空(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);
演示
关于MYSQL - 如果表为空则插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49941928/