我的表:
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 錯誤 [1064] [42000]:您的 SQL 語法有錯誤;檢查與您的 MariaDB 服務器版本相對應的手冊,以了解在第 4 行的 '' 附近使用的正確語法
更新:我知道 IF/ELSE 只能在程序/函式中使用,但我希望我們可以做類似的事情。任何幫助將不勝感激??
“保羅·T。” 答:如果值可以在插入時引發 SQL 錯誤(如唯一鍵或外鍵),您可以使用INSERT IGNORE如下方式。
INSERT IGNORE INTO FirstTable
(label, SecondTable_id) VALUES
('Str Test', (SELECT id FROM SecondTable WHERE label = 'Str Match'));
uj5u.com熱心網友回復:
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')
uj5u.com熱心網友回復:
這是僅當目標表中不存在時才插入的兩種方法。
第一個是程式性的,從選擇插入。
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;
第二個是從帶有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<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/366523.html
上一篇:SQLwhereKey="Test"andID=max(ID)
下一篇:從資料庫SQL中的列中獲取日期
