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.
答案 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'
)