MYSQL-如果表为空则插入
问题描述:
如果表为空(0行),我想在表上插入一些数据.
I want to insert some data on my table if the table is empty (0 rows).
我尝试过:
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;
但是我明白了
错误代码:1064.您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在'IF NOT EXISTS(SELECT account_types)然后在第1行插入'account_types'中使用
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
What can I do ? I'm using 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);
演示