子查询
子查询(Subquery)是指出现在其他SQL语句内的SELECT子句。
例如:
SELECT * FROM t1 WHERE col1=(SELECT col2 FROM t2);
其中,SELECT * FROM t1,称为Outer Query/Outer Statement
SELECT col2 FROM t2,称为SubQuery
子查询指嵌套在查询内部,且必须始终出现在圆括号内。
子查询可以包含多个关键字或条件,如DISTINCT、GROUP BY、ORDER BY、LIMIT,函数等。
子查询的外层查询可以是:SELECT,INSERT,UPDATE,SET或DO。
子查询可以返回标量、一行、一列或子查询。
使用比较运算符的子查询
=、<、>、>=、<=、<>、!=、<=>
语法结构
operand comparison_operator subquery
例子:
SELECT goods_id,goods_name,goods_price FROM goods WHERE goods_price >= (SELECT ROUND(AVG(goods_price),2) FROM goods);
用ANY、SOME或ALL修饰比较运算符
operand comparison_operator ANY (subquery)
operand comparison_operator SOME (subquery)
operand comparison_operator ALL (subquery)
如果子查询返回多个结果,需要使用上面三个关键字。
例子:
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price > ANY (SELECT goods_price FROM tdb_goods WHERE goods_cate=’超极本’);
使用[NOT] IN 的子查询
语法结构
operand comparison_operator [NOT] IN (subquery)
=ANY 运算符与IN等效
!=ALL或<>ALL运算符与NOT IN 等效
例子:
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price IN (SELECT goods_price FROM tdb_goods WHERE goods_cate=’超极本’);
使用[NOT] EXISTS的子查询
如果子查询返回任何行,EXISTS将返回TRUE;否则为FALSE。
INSERT...SELECT
将查询结果写入数据表
INSERT [INTO] tbl_name [(col_name,...)] SELECT ...
例子:
CREATE TABLE IF NOT EXISTS goods_cates(
cate_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
cate_name VARCHAR(40)
);
INSERT goods_cates(cate_name) SELECT goods_cate FROM goods GROUP BY good_cate;