MySQL子查询

子查询定义

子查询是指出现在其他SQL语句内的SELECT子句

SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2); 
  • SELECT * FROM t1 ... 称为Outer Query(外查询)(或Outer Statement)
  • SELECT column1 FROM t2 称为Sub Query(子查询)
  1. 子查询指嵌套在 查询内部,且必须始终出现在 圆括号内
  2. 子查询可以包含多个关键字或者条件,如DISTINCT,GROUP BY,ORDER BY,LIMIT,函数
  3. 子查询的外层查询可以是:SELECT,INSERT,UPDATE,SET,DO
  4. 子查询的返回值可以是:标量、一行、一列,甚至是另一个子查询

比较运算符的子查询

比较运算符: =、>、<、>=、<=、<>、!=、<=>

查找价格大于平均值的商品

单独查询时:

--AVG函数代表求其平均值
SELECT AVG(goods_price) FROM tdb_goods;
--round(@,#)代表输出格式为@数小数点后#位输出 
SELECT ROUND(AVG(goods_price),2) FROM tdb_goods;     
--输出价格大于5391.30的id、name、price
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price>=5391.30; 

运用子查询时:

--查找价格大于平均值的商品
SELECT goods_id,goods_name,goods_price 
FROM tdb_goods 
WHERE goods_price>=
    (SELECT ROUND(AVG(goods_price),2) 
        FROM tdb_goods);     
查询价格比超极本价格贵的商品

\g:等价于";"
\G:将查询到的横向表格纵向输出,方便阅读

--检索结果非唯一
SELECT goods_price FROM tdb_price WHERE goods_cate='超级本'\G;
--需要用ANY、SOME、ALL

对于ANY、SOME、ALL的用法各有不同:

SELECT goods_id,goods_name,goods_price 
FROM tdb_goods WHERE goods_price>=ANY 
(SELECT goods_price FROM tdb_goods WHERE goods_cate='超级本');

SELECT goods_id,goods_name,goods_price 
FROM tdb_goods WHERE goods_price>=ALL 
(SELECT goods_price FROM tdb_goods WHERE goods_cate='超级本');

SELECT goods_id,goods_name,goods_price 
FROM tdb_goods WHERE goods_price>=SOME 
(SELECT goods_price FROM tdb_goods WHERE goods_cate='超级本');

[NOT] IN / EXISTS的子查询

IN / NOT IN

IN 相当于 =ANY=SOME 表示包含
NOT IN 相当于 !=ALL 或者 <>ALL 表示不包含

EXISTS / NOT EXISTS

用得比较少,子查询结果非空(返回任何行), EXISTS 返回 true ,反之返回 false.

SELECT goods_id,goods_name,goods_price 
FROM tdb_goods WHERE goods_price IN 
(SELECT goods_price FROM tdb_goods WHERE goods_cate = '超级本')

你可能感兴趣的:(mysql)