Search code examples
mysqlsqldatabasesql-insertdatabase-administration

How to map value to sinle id in mysql?


I have below 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 timetsamp article
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 mno 2021-06-18 185

Table PQR

SID statid institutionid
1 2 22
2 3 33
3 1 44
4 8 55
5 9 66

I want to compare id from ABC with statid from PQR. if id is not present in PQR table then it should insert to PQR table with institutionid value '999' along with id. For example id 4 from ABC not present in statid from PQR, so it should made insert with new row 4,999.

Sample output

sid statid institutionid
1 2 22
2 3 33
3 1 44
4 8 55
5 9 66
6 4 999
7 5 999

Here id 4 and 5 are not present, so it inserted 2 row with id and constant institutionid value.

How can achieve by using query?


Solution

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

    If you create unique index for pqr (statid) then the query can be simplified till

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