多语言展示
当前在线:1293今日阅读:84今日分享:32

Mysql常见子查询语句

常见子查询语句形式:where  字段  比较运算符  (标量子查询);因为其相当于:where  字段  比较运算符  一个具体值;  //比如:where  age > 18
工具/原料

Mysql常见子查询语句

使用in的子查询

形式:where  字段  in  (列子查询);这里,列子查询可能是“多个值”,虽然查询的输出结果是“一列”的,但我们要理解为是“多个值的列表”,其相当于:where  字段  in (值1,值2,....);比如: where  age  in (18, 28, 38); 表示age为其中任意一个就可以举例:找出跟索尼品牌的商品的产地相同产地的商品;select  *  from  product  where  chandi in ( select chandi  from product  where pinpai = ‘索尼’ );

使用any的子查询
1

形式:where  字段  比较运算符  any  (列子查询);含义:表示,该字段的值,对该列子查询所查询出来的多个值,有一个满足该比较运算符,就算满足了。举例:表:tab1

2

elect  * from  tab1  where  f2  = any (select  n2  from  tab2 );则表示f2的值,等于该子查询的任何其中一个值,就算满足了该“相等”判断。当前,其相当于:select  * from  tab1  where  f2  in  (select  n2  from  tab2 ); 继续举例:select  * from  tab1  where  f2  <  any (select  n2  from  tab2 ); //此时tab1中的2行都取出但如果:select  * from  tab2  where  n2  <  any (select  f2  from  tab1 ); //此时tab2中的n1=11的行取出可见:any就是“其中之一”的意思。

3

使用的子查询形式:where  字段  比较运算符  some  (列子查询);含义:同any。即some是any的同义词。

使用all的子查询:
1

形式:where  字段  比较运算符  all  (列子查询);含义:表示,该字段的值,要对该列子查询的所有结果数据,全都满足该运算符,才算符合条件。举例:表:tab1

2

继续举例:select  * from  tab2  where  n2  >  all (select  f2  from  tab1 ); //此时tab2中的n1=12的行取出select  * from  tab2  where  n2  <  all (select  f2  from  tab1 ); //此时结果为“空结果集”(即0行)

使用exists的子查询
1

形式:where  exists ( 任何子查询 )含义:该子查询如果“有数据结果”, 则该exists()的结果为“true”该子查询如果“没有数据结果”,则该exists()的结果为“false”特别注意:1,该子查询,如果其仅仅是为了得到“有没有数据”的结果,则通常此时对主查询就失去应用意义;2,实际上,该子查询,通常都需要在子查询(内部)中来使用主查询(外部)的某些字段作为条件数据,这样才能具有一定的实用意义。其实,这种情况下的子查询,对于mysql内部,是做了“内连接之后”的结果。举例1:select * from product where exists(    select * from product_type        where product_type.protype_id = product.protype_id            and protype_name like '%码%');

2

举例2:

3

举例3:

推荐信息