为此,您可以将子查询与EXISTS一起使用。让我们首先创建一个表-
mysql> create table DemoTable1 -> ( -> Id int, -> SubjectName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1 values(111,'MySQL'); mysql> insert into DemoTable1 values(112,'MongoDB'); mysql> insert into DemoTable1 values(113,'Java'); mysql> insert into DemoTable1 values(114,'C'); mysql> insert into DemoTable1 values(115,'MySQL');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1;
这将产生以下输出-
+------+-------------+ | Id | SubjectName | +------+-------------+ | 111 | MySQL | | 112 | MongoDB | | 113 | Java | | 114 | C | | 115 | MySQL | +------+-------------+ 5 rows in set (0.00 sec)
这是创建第二个表的查询-
mysql> create table DemoTable2 -> ( -> FirstName varchar(20), -> StudentSubject varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable2 values('Chris','MySQL'); mysql> insert into DemoTable2 values('Bob','MySQL'); mysql> insert into DemoTable2 values('Sam','MySQL'); mysql> insert into DemoTable2 values('Carol','C');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable2;
这将产生以下输出-
+-----------+----------------+ | FirstName | StudentSubject | +-----------+----------------+ | Chris | MySQL | | Bob | MySQL | | Sam | MySQL | | Carol | C | +-----------+----------------+ 4 rows in set (0.00 sec)
这是只从一个表中选择数据的查询,该表中的列值与另一张表的列值相匹配-
mysql> select Id from DemoTable1 -> where exists -> ( -> select 1 from DemoTable2 -> where SubjectName=StudentSubject -> );
这将产生以下输出-
+------+ | Id | +------+ | 111 | | 114 | | 115 | +------+ 3 rows in set (0.00 sec)