含有IN的子查询特点:
含有IN的子查询格式:
SELECT select_list
FROM table_source
WHERE search_expression [NOT] IN (subquery)
注:语句中的search_expression可以是变量值,列名,表达式或子查询
实例:
# Create Table Customers
create table Customers(
CustID int not null primary key,
CustName char(20) not null,
City char(20) not null
);
# Create Table OderHeader
create table OrderHeader(
CustID int not null,
OrderID int not null,
OrderDate datetime not null,
ShipTo char(20) not null,
foreign key(CustID) references Customers(CustID)
);
# Put the values into table Customers
insert into Customers values
(1, 'Name_A', 'BeiJing'),
(2, 'Name_B', 'ShangHai'),
(3, 'Name_C', 'BeiJing'),
(4, 'Name_D', 'BeiJing');
# Put the values into table OrderHeader
insert into OrderHeader values
(1, 110, '2018-07-01', 'FangShan , BeiJing'),
(1, 111, '2018-07-01', 'HaiDian , BeiJing'),
(2, 113, '2018-07-02', 'PuDong , ShangHai'),
(3, 114, '2018-07-03', 'ChangPing , BeiJing');
# Table Customers
+--------+----------+----------+
| CustID | CustName | City |
+--------+----------+----------+
| 1 | Name_A | BeiJing |
| 2 | Name_B | ShangHai |
| 3 | Name_C | BeiJing |
| 4 | Name_D | BeiJing |
+--------+----------+----------+
# Table OrderHeader
+--------+---------+---------------------+---------------------+
| CustID | OrderID | OrderDate | ShipTo |
+--------+---------+---------------------+---------------------+
| 1 | 110 | 2018-07-01 00:00:00 | FangShan , BeiJing |
| 1 | 111 | 2018-07-01 00:00:00 | HaiDian , BeiJing |
| 2 | 113 | 2018-07-02 00:00:00 | PuDong , ShangHai |
| 3 | 114 | 2018-07-03 00:00:00 | ChangPing , BeiJing |
+--------+---------+---------------------+---------------------+
# SQL 语句
select OrderID, OrderDate, ShipTo
from OrderHeader
where CustID in (1, 3, 4);
# 结果
+---------+---------------------+---------------------+
| OrderID | OrderDate | ShipTo |
+---------+---------------------+---------------------+
| 110 | 2018-07-01 00:00:00 | FangShan , BeiJing |
| 111 | 2018-07-01 00:00:00 | HaiDian , BeiJing |
| 114 | 2018-07-03 00:00:00 | ChangPing , BeiJing |
+---------+---------------------+---------------------+
# SQL语句
select O.*
from OrderHeader as O
where OrderID in
(select OrderID from Customers as C where C.City = 'BeiJing');
# 结果
+--------+---------+---------------------+---------------------+
| CustID | OrderID | OrderDate | ShipTo |
+--------+---------+---------------------+---------------------+
| 1 | 110 | 2018-07-01 00:00:00 | FangShan , BeiJing |
| 1 | 111 | 2018-07-01 00:00:00 | HaiDian , BeiJing |
| 2 | 113 | 2018-07-02 00:00:00 | PuDong , ShangHai |
| 3 | 114 | 2018-07-03 00:00:00 | ChangPing , BeiJing |
+--------+---------+---------------------+---------------------+
注:上面的查询语句为一个独立子查询,可以单独执行