Query table A and table B has records at the same time, table A exists and table B does not have records, table B exists and table A does not have records.

Keywords: SQL

1. problem

Query table A and table B has records at the same time, table A exists and table B does not have records, table B exists and table A does not have records.

As shown above, where:

Area A is a collection of old tables and new tables.
The C region is a collection of new tables and old tables.
Area B is a common set of old and new tables.

Q: The table structure of the known old table is the same as that of the new table.

2. Scene simulation solution

The following two tables are old table and new table. The structure of the table is identical as follows:

/*Table structure for table `new` */

DROP TABLE IF EXISTS `new`;

CREATE TABLE `new` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

/*Data for the table `new` */

insert  into `new`(`id`,`name`,`age`) values (1,'Liu Bei',11),(2,'Guan Yu',12),(3,'Zhang Fei',13),(4,'Zhao Yun',1),(5,'Zhu Geliang',24);

/*Table structure for table `old` */

DROP TABLE IF EXISTS `old`;

CREATE TABLE `old` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

/*Data for the table `old` */

insert  into `old`(`id`,`name`,`age`) values (1,'Zhao Yun',1),(2,'Liu Bei',11),(3,'Zhu Geliang',14),(4,'Zhang Fei',23);

The old table records:

id  name    age
1   Zhao Yun    1
2   Liu Bei    11
3   Zhu Geliang  14
4   Zhang Fei    23

The new table has records:

id  name    age
1   Liu Bei    11
2   Guan Yu    12
3   Zhang Fei    13
4   Zhao Yun    1
5   Zhu Geliang  24

3. sql code resolution

Field name, age same record is treated as same record

/* old Records shared by tables and new tables */
SELECT t1.name, t1.age FROM `old` t1, `new` t2 WHERE t1.name = t2.name AND t1.age = t2.age;

/* Result */
name    age
//Liu Bei 11
//Zhao Yun 1
/* old There are no records in the new table. */
SELECT t1.name, t1.age FROM `old` t1 WHERE NOT EXISTS (SELECT 1 FROM `new` t2 WHERE t1.name = t2.name AND t1.age = t2.age);

/* Result */
name    age
//Zhuge Liang 14
//Zhang Fei 23
/* new There are no records in old table. */
SELECT t2.name, t2.age FROM `new` t2 WHERE NOT EXISTS (SELECT 1 FROM `old` t1 WHERE t1.name = t2.name AND t1.age = t2.age);

/* Result */
name    age
//Guan Yu 12
//Zhang Fei 13
//Zhuge Liang 24

OK, Enjoy it!

Posted by php_gromnie on Thu, 14 Feb 2019 17:06:18 -0800