简体   繁体   English

SQL-如果没有数据,则插入表中

[英]SQL - Insert into table if doesn't have data

I'm using MYSQL script and I want to insert some values in a table. 我正在使用MYSQL脚本,并且想在表中插入一些值。

INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');

But I only want to insert if the table is empty in the first place. 但是我只想在表为空的情况下插入。

I'm not a SQL guy but basically 我不是SQL专家,但基本上

if(testType.length() == 0 {

    INSERT INTO `testType` (`name`) VALUES ('URL');
    INSERT INTO `testType` (`name`) VALUES ('xD');
    INSERT INTO `testType` (`name`) VALUES ('LOL');

}

How can I do this the simplest and smallest way possible? 我该如何以最简单和最小的方式做到这一点? Thank you. 谢谢。

EDIT: my question is different. 编辑:我的问题是不同的。 I want to insert ALL THE DATA if the table is empty. 如果表为空,我想插入所有数据。 not only one insert at the time 一次只插入一个

First, I would suggest doing this in one step: 首先,我建议一步来做:

INSERT INTO testType(name)
    VALUES ('URL'), ('xD'), ('LOL');

Then, you can express this without IF : 然后,您可以不使用IF来表达这一点:

INSERT INTO testType(name)
    SELECT t.name
    FROM (SELECT 'URL' as name UNION ALL
          SELECT 'xD' as name UNION ALL
          SELECT 'LOL' as name
         ) t
    WHERE NOT EXISTS (SELECT 1 FROM testType);

Finally, if you want to insert these values if each doesn't exist, then you can let the database do the work. 最后,如果您想在每个值都不存在的情况下插入这些值,则可以让数据库完成这些工作。 First, define a unique constraint/index on the name (if name is not already the primary key), and then use ON DUPLICATE KEY UPDATE : 首先,在name上定义唯一的约束/索引(如果名称还不是主键),然后使用ON DUPLICATE KEY UPDATE

CREATE UNIQUE INDEX unq_testtable_name ON testtable(name);

INSERT INTO testType(name)
    VALUES ('URL'), ('xD'), ('LOL')
    ON DUPLICATE KEY UPDATE name = VALUES(name);

Try this: 尝试这个:

DECLARE @ExistCount INT;
SET @ExistCount = (SELECT COUNT(1) FROM `testType`);

IF @ExistCount<1
THEN
    INSERT INTO `testType` (`name`) VALUES ('URL'),('xD'),('LOL');
END IF;

You can use stored procedure 您可以使用存储过程

DELIMITER //

CREATE PROCEDURE `proc1` ()
BEGIN

        SELECT COUNT(*) INTO variable1 FROM testType;
        IF variable1 = 0 THEN
            INSERT INTO `testType` (`name`) VALUES ('URL');
            INSERT INTO `testType` (`name`) VALUES ('xD');
            INSERT INTO `testType` (`name`) VALUES ('LOL');
    END WHILE;
END //

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM