4

在这个问题之后,我一直在尝试模仿正确的答案,仅当表格为空时才在表格中插入数据。

如果表为空,则执行 INSERT?

这是我的代码:

INSERT INTO `statuses` SELECT 
    ('Something', 'Something else', 123),
    ('Something', 'Something else', 234)
    WHERE NOT EXISTS (SELECT * FROM `statuses`);

但是,如果表为空,我不会添加元素,而是得到:

#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 'WHERE NOT EXISTS (SELECT * FROM `statuses`)'

我应该如何编写查询以便仅在表为空时才插入值?

4

2 回答 2

3

您的语句中有语法错误:

INSERT INTO `statuses`
    (SELECT  'Something', 'Something else', 123
     WHERE NOT EXISTS (SELECT * FROM `statuses`)
    ) union all
    (SELECT 'Something', 'Something else', 234
     WHERE NOT EXISTS (SELECT * FROM `statuses`)
    );

在这种情况下,您需要重复where两次,每个子查询一次。你也可以这样做:

INSERT INTO `statuses`
    select t.*
    from ((SELECT  'Something' as col1, 'Something else' as col2, 123 as col3
          ) union all
          (SELECT 'Something', 'Something else', 234
          )
         ) t
    WHERE NOT EXISTS (SELECT * FROM `statuses`);

在此版本中,您需要为列分配名称。

或者,您可以只使用两个单独的插入语句。

于 2013-03-25T01:06:57.650 回答
1

正确的语法是:

INSERT INTO user_authentication
SELECT t.*
FROM ((SELECT 1 as col1, 'kingston' as col2, 'test' as col3, true as col4)) t
WHERE NOT EXISTS (SELECT * FROM user_authentication);

这对我有用。

于 2014-08-21T09:34:12.783 回答