从 MySQL 中的两个表中提取相似的 ID 记录
首先创建一个表 −
mysql> create table DemoTable1 ( Id int ); Query OK, 0 rows affected (1.26 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1 values(100); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1 values(110); Query OK, 1 row affected (0.49 sec) mysql> insert into DemoTable1 values(4); Query OK, 1 row affected (0.44 sec) mysql> insert into DemoTable1 values(3); Query OK, 1 row affected (0.18 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable1;
这将产生以下输出 −
+------+ | Id | +------+ | 100 | | 110 | | 4 | | 3 | +------+ 4 rows in set (0.00 sec)
以下是创建第二个表的查询 −
mysql> create table DemoTable2 ( Id int, Name varchar(50) ); Query OK, 0 rows affected (0.78 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable2 values(4,'Chris'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable2 values(1,'David'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable2 values(110,'Adam'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable2 values(210,'Bob'); Query OK, 1 row affected (0.19 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable2;
这将产生以下输出 −
+------+-------+ | Id | Name | +------+-------+ | 4 | Chris | | 1 | David | | 110 | Adam | | 210 | Bob | +------+-------+ 4 rows in set (0.00 sec)
以下是从 MySQL 中两个表中提取相似 ID 记录的查询 −
mysql> select Id,Name from DemoTable2 where Id IN (select Id from DemoTable1);
这将产生以下输出 −
+------+-------+ | Id | Name | +------+-------+ | 110 | Adam | | 4 | Chris | +------+-------+ 2 rows in set (0.39 sec)
广告