在 MySQL 中用条件连接两个表?

mysqlmysqli database

要连接两个表,请在 MySQL 中使用 UNION ALL。让我们创建一个表 −

mysql> create table DemoTable1
   (
   Id int,
   FirstName varchar(20)
   );
Query OK, 0 rows affected (1.52 sec)

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

mysql> insert into DemoTable1 values(10,'John');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable1 values(20,'Carol');
Query OK, 1 row affected (0.28 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable1;

输出

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 10   | John      |
| 20   | Carol     |
+------+-----------+
2 rows in set (0.00 sec)

Create second table.

mysql> create table DemoTable2
   (
   Id int,
   FirstName varchar(20)
   );
Query OK, 0 rows affected (1.22 sec)

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

mysql> insert into DemoTable2 values(20,'David');
Query OK, 1 row affected (1.28 sec)
mysql> insert into DemoTable2 values(40,'Chris');
Query OK, 1 row affected (0.38 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable2;

输出

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 20   | David     |
| 40   | Chris     |
+------+-----------+
2 rows in set (0.00 sec)

以下是连接两个表的查询 −

mysql> select *from DemoTable1 where Id=20
   union all select *from DemoTable2 where Id=20;

输出

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 20   | Carol     |
| 20   | David     |
+------+-----------+
2 rows in set (0.43 sec)

相关文章