从MySQL中的两个表中获取相似的ID记录

让我们首先创建一个表-

mysql> create table DemoTable1
(
   Id int
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable1 values(100);
mysql> insert into DemoTable1 values(110);
mysql> insert into DemoTable1 values(4);
mysql> insert into DemoTable1 values(3);

使用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)
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable2 values(4,'Chris');
mysql> insert into DemoTable2 values(1,'David');
mysql> insert into DemoTable2 values(110,'Adam');
mysql> insert into DemoTable2 values(210,'Bob');

使用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)
猜你喜欢