mysql>desc offices;+--------------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+--------------+-------------+------+-----+---------+-------+| officeCode | varchar(10) | NO | PRI | NULL | || city | varchar(50) | NO | | NULL | || phone | varchar(50) | NO | | NULL | || addressLine1 | varchar(50) | NO | | NULL | || addressLine2 | varchar(50) | YES | | NULL | || state | varchar(50) | YES | | NULL | || country | varchar(50) | NO | | NULL | || postalCode | varchar(15) | NO | | NULL | || territory | varchar(10) | NO | | NULL | |+--------------+-------------+------+-----+---------+-------+9rowsinset
如果您想查找位于美国和法国的办事处,可以使用IN运算符作为以下查询:
SELECT officeCode, city, phone, countryFROM officesWHERE country IN ('USA' , 'France');
执行上面查询语句,得到以下结果
mysql>SELECT officeCode, city, phone, country FROM offices WHERE country IN ('USA' , 'France');+------------+---------------+-----------------+---------+| officeCode | city | phone | country |+------------+---------------+-----------------+---------+| 1 | San Francisco | +16502194782 | USA || 2 | Boston | +12158370825 | USA || 3 | NYC | +12125553000 | USA || 4 | Paris | +33147234404 | France |+------------+---------------+-----------------+---------+4rowsinset
也可以使用OR运算符执行得到与上面查询相同的结果,如下所示:
SELECT officeCode, city, phoneFROM officesWHERE country ='USA'OR country ='France';
执行上面查询语句,得到以下结果
mysql>SELECT officeCode, city, phone FROM offices WHERE country ='USA'OR country ='France';+------------+---------------+-----------------+| officeCode | city | phone |+------------+---------------+-----------------+| 1 | San Francisco | +16502194782 || 2 | Boston | +12158370825 || 3 | NYC | +12125553000 || 4 | Paris | +33147234404 |+------------+---------------+-----------------+4rowsinset
SELECT officeCode, city, phoneFROM officesWHERE country NOTIN ('USA' , 'France');
执行上面查询语句,得到以下结果
mysql>SELECT officeCode, city, phone FROM offices WHERE country NOTIN( 'USA', 'France');+------------+---------+------------------+| officeCode | city | phone |+------------+---------+------------------+| 5 | Beijing | +86332245000 || 6 | Sydney | +61292642451 || 7 | London | +442078772041 |+------------+---------+------------------+3rowsinset
MySQL IN 与子查询
IN运算符通常用于子查询。子查询不提供常量值列表,而是提供值列表。
我们来看看两张表:orders和orderDetails表的结构以及它们之间的关系:
例如,如果要查找总金额大于60000的订单,则使用IN运算符查询如下所示:
SELECT orderNumber, customerNumber, status, shippedDateFROM ordersWHERE orderNumber IN (SELECT orderNumberFROM orderDetailsGROUP BY orderNumberHAVINGSUM(quantityOrdered * priceEach) >60000);