如何将值映射到 mysql 中的单个 ID?

How to map value to sinle id in mysql?

我有以下 2 tables

CREATE TABLE ABC(
  id int(11) NOT NULL AUTO_INCREMENT,
  joveuser varchar(64) DEFAULT NULL,
  timestamp date NOT NULL DEFAULT '0000-00-00',
  Article int(6) DEFAULT NULL,
  PRIMARY KEY (id,timestamp)
);

CREATE TABLE PQR(
  id int(11) NOT NULL AUTO_INCREMENT,
  statid int(11) NOT NULL,
  institutionid int(11) NOT NULL,
  PRIMARY KEY (id,institutionid),
  UNIQUE KEY statid_2 (statid,institutionid),
  KEY statid (statid),
  KEY institutionid (institutionid)
) ;

Table ABC

id joveuser 时间戳 文章
1 abc 2021-02-15 85
2 def 2021-04-25 113
3 ghi 2021-05-01 63
4 jkl 2021-05-28 22
5 没有 2021-06-18 185

Table PQR

SID statid 机构编号
1 2 22
2 3 33
3 1 44
4 8 55
5 9 66

我想比较 ABCidstatid PQR。如果 id 不存在于 PQR table 中,那么它应该插入到 PQR table 中,institutionid 值为 '999' 以及 id。例如 id 4 来自 ABC 不存在于来自 PQR[=139 的 statid =],所以它应该插入新行 4,999。

示例输出

sid statid 机构编号
1 2 22
2 3 33
3 1 44
4 8 55
5 9 66
6 4 999
7 5 999

此处不存在 id 4 和 5,因此它插入了 2 行,id 和常量 institutionid 值。

如何使用查询实现?

INSERT INTO pqr (statid, institutionid)
SELECT id, 999
FROM abc
WHERE NOT EXISTS ( SELECT NULL
                   FROM pqr
                   WHERE abc.id = pqr.statid )

如果为 pqr (statid) 创建唯一索引,则查询可以简化到

INSERT IGNORE INTO pqr (statid, institutionid)
SELECT id, 999
FROM abc