如果行不存在,如何插入? (询问)

How insert if a row not already exists ? (query)

我的表:

FirstTable
--------------------
'id' INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT
'label' VARCHAR(255) UNIQUE NOT NULL
'secondTable_id' INT(11) UNIQUE NOT NULL


SecondTable
--------------------
'id' INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT
'label' VARCHAR(255) UNIQUE NOT NULL

错误的迁移脚本:

IF ('Str Test' NOT IN (SELECT label from FirstTable)) THEN 
    INSERT INTO FirstTable
    (label, secondTable_Id) VALUES 
    ('Str Test', (SELECT id FROM SecondTable WHERE label = 'Str Match'));
END IF;

如果 FirstTable.label == Str Test 不存在,我会尝试插入新行,但出现错误:

SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 4


更新:我知道 IF/ELSE 只能在 procedure/function 中使用,但我希望我们可以做类似的事情。任何帮助将不胜感激❤️


'Paul T.' 回答: 如果值可以在插入时抛出 SQL 错误(如唯一键或外键),您可以像下面那样使用 INSERT IGNORE

INSERT IGNORE INTO FirstTable
    (label, SecondTable_id) VALUES 
    ('Str Test', (SELECT id FROM SecondTable WHERE label = 'Str Match'));
INSERT INTO FirstTable(label, secondTable_Id)
SELECT 'Str Test', id 
FROM SecondTable 
WHERE label = 'Str Match' and not exists(
                            select * 
                            from FirstTable 
                            where label = 'Str Test')

这里有两种插入方式,仅当它不存在于目标中时才插入 table。

第一个是程序性的,插入来自 select。

SET @FirstLabel = 'Str Test';
SET @SecondLabel = 'Str Match';
IF NOT EXISTS (SELECT 1 from FirstTable WHERE label = @FirstLabel) 
THEN 
    INSERT INTO FirstTable (label, secondTable_Id) 
    SELECT @FirstLabel, id 
    FROM SecondTable 
    WHERE label = @SecondLabel
    ORDER BY id DESC
    LIMIT 1;
END IF;

第二个是来自 select 和 NOT EXISTS 的插入。

SET @FirstLabel = 'Str Test';
SET @SecondLabel = 'Str Match';
INSERT INTO FirstTable (secondTable_Id, label) 
SELECT t2.id, @FirstLabel
FROM SecondTable t2
WHERE t2.label = @SecondLabel
  AND NOT EXISTS (
     SELECT 1
     FROM FirstTable t1
     WHERE t1.secondTable_Id = t2.id
       AND t1.label = @FirstLabel
  )
ORDER BY t2.id DESC
LIMIT 1;

db<>fiddle here