在非关键字段

时间:2015-09-06 11:35:46

标签: mysql sql sql-insert

如果我想在带有字段的表中插入多个值:

ID | name | content  
---+------+------------------
 1 | john | some content  
 2 | bob  | another content

现在我想插入多个值:

INSERT INTO persons (name,content)
VALUES
("Foo","meh"),
("Moo","beh"),
("bob","huh"),
("dude","haha")

结果应该是:

ID | name | content  
---+------+------------------
 1 | john | some content  
 2 | bob  | another content
 3 | Foo  | meh
 4 | Moo  | beh
 5 | dude | haha

查询按名称忽略重复项,因此未插入“bob”|“huh”,名称不是键字段。我找不到任何语法,我知道它应该是简单的。

我正在使用MySQL数据库。

2 个答案:

答案 0 :(得分:3)

使用LEFT JOIN确定记录是否已在表

<强> SqlFiddleDemo

CREATE TABLE persons(ID INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(100),
      content VARCHAR(100));

INSERT INTO persons (name, content)
VALUES ('john', 'some content'), ('bob', 'another content');

INSERT INTO persons (name,content)
SELECT t.name, t.content
FROM
(
  SELECT "Foo" AS name,"meh" AS content
  UNION ALL
  SELECT "Moo","beh"
  UNION ALL
  SELECT "bob","huh"
  UNION ALL
  SELECT "dude","haha"
) AS t
LEFT JOIN persons p
ON p.name = t.name
WHERE p.id IS NULL;

SELECT *
FROM persons;

使用NOT EXISTS

相同
INSERT INTO persons (name,content)
SELECT t.name, t.content
FROM
(
  SELECT "Foo" AS name,"meh" AS content
  UNION ALL
  SELECT "Moo","beh"
  UNION ALL
  SELECT "bob","huh"
  UNION ALL
  SELECT "dude","haha"
) AS t
WHERE NOT EXISTS 
     (SELECT 1 FROM persons p WHERE p.name = t.name)

修改

添加UNIQUE KEY并使用INSERT IGNORE INTO

<强> SqlFiddleDemo

CREATE TABLE persons(ID INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(100) UNIQUE KEY,
      content VARCHAR(100));

INSERT INTO persons (name, content)
VALUES ('john', 'some content'), ('bob', 'another content');


INSERT IGNORE INTO persons (name,content)
VALUES
("Foo","meh"),
("Moo","beh"),
("bob","huh"),
("dude","haha");

SELECT *
FROM persons;

答案 1 :(得分:1)

这是在tsql中,但您可以使用合并语句创建存储过程,该合并语句具有表类型(名称和内容作为列)作为参数,以在插入之前检查名称。如果名称匹配则不会插入但如果不匹配则会插入新记录。

BEGIN TRANSACTION

-- setup tables for merge
MERGE dbo.persons AS t

USING @NameContentTable AS s
    ON t.name = s.name      

-- do nothing if matched

-- insert if not matched
WHEN NOT MATCHED THEN   
    INSERT (name, 
            content)
    VALUES (s.name,
            s.content);

-- error handling
IF @@ERROR <> 0 
BEGIN
    SELECT 'Unexpected error occurred'
    ROLLBACK TRAN 
    RETURN -1
END

COMMIT TRANSACTION