如果不存在,添加名称+代码到缓冲区?

时间:2014-03-07 20:53:09

标签: mysql

CREATE TABLE item(
code TINYINT UNSIGNED NOT NULL,
name CHAR(20) NOT NULL,
UNIQUE KEY(name, code)) ENGINE = INNODB

CREATE TABLE buffer(
code TINYINT UNSIGNED NOT NULL,
name CHAR(20) NOT NULL,
PRIMARY KEY(name, code)) ENGINE = INNODB

如何仅使用一个语句执行以下操作:if name+code doesn't exist in any table then add them on buffer.

1 个答案:

答案 0 :(得分:1)

使用EXISTS语句作为子查询,如下所示:

INSERT INTO buffer (code, name)
SELECT 1,'myname' FROM dual
WHERE NOT EXISTS (
  SELECT * FROM item WHERE code=1 and name='myname'
  UNION
  SELECT * FROM buffer WHERE code=1 and name='myname'
)

工作小提琴:http://sqlfiddle.com/#!2/4ecc66/1