Mariadb

MariaDB:如果不存在,則將記錄(元組列表)插入表中

  • March 13, 2021

目前我有幾個看起來像這樣的 sql 查詢:

INSERT INTO `test` (col1, col2)
SELECT * FROM (SELECT '1','2') AS tmp
WHERE NOT EXISTS (
   SELECT * FROM `test`
   WHERE col1='1' AND col2='2'
) LIMIT 1;


INSERT INTO `test` (col1, col2)
SELECT * FROM (SELECT '3','4') AS tmp
WHERE NOT EXISTS (
   SELECT * FROM `test`
   WHERE col1='3' AND col2='4'
) LIMIT 1;

一般來說,根據經驗,查詢越少越好,這就是為什麼我想將 sql 查詢重寫為一個查詢。當擁有數百萬個數據集時,這應該會更快,因為WHERE子句只會遍歷表一次,因此這應該是可能的:

WHERE col1 in ('1','3') AND col2 in ('2','4')

但是當我在單個查詢中嘗試多個選擇語句時,例如:

SELECT * FROM 
(SELECT '1','2') AS tmp1,
(SELECT '3','4') AS tmp2

SQL 拋出此錯誤:

#1136 - Column count doesn't match value count at row 1

問題出在SELECT * FROM (SELECT '1','2') AS tmp.

如何(1, 2) (3, 4)在子查詢中使用多個元組來滿足WHERE條件?

有沒有更短、更快的方法來實現這一目標?

任何回饋都非常感謝!

請忽略數據類型;數字的格式應為intnot as varchar


更新

執行以下操作時:

INSERT INTO `test` (col1, col2)
SELECT * FROM
((SELECT * FROM (SELECT '7','8') AS tmp
WHERE NOT EXISTS (
   SELECT * FROM `test`
   WHERE col1='7' AND col2='8'
) LIMIT 1)
UNION
(SELECT * FROM (SELECT '9','9') AS tmp
WHERE NOT EXISTS (
   SELECT * FROM `test`
   WHERE col1='9' AND col2='9'
) LIMIT 1)) t1;

SQL 拋出:Duplicate column name '9'

您可以根據UNION ALL需要建構盡可能多的行:

INSERT INTO test
SELECT
 i.col1
,i.col2
FROM
 (
   SELECT 
     1 AS col1
    ,2 AS col2
   
     UNION ALL
     
   SELECT 
     3
    ,4
 )  i
WHERE
 NOT EXISTS
   (
     SELECT
       1
     FROM
       test
     WHERE
       col1 = i.col1
         AND col2 = i.col2
   )

在這裡看小提琴。

在 10.3.3 MariaDB(有點)支持表值建構子之後,您將無法像其他方式那樣命名列:

INSERT INTO test
SELECT
 i.`1`
,i.`2`
FROM
 (
   VALUES
     (1,2)
    ,(3,4)
 )  i
WHERE
 NOT EXISTS
   (
     SELECT
       1
     FROM
       test
     WHERE
       col1 = i.`1`
         AND col2 = i.`2`
   )

引用自:https://dba.stackexchange.com/questions/286856