子查询(Subquery)是指出现在其他SQL语句内的SELECT子句。
例如:
SELECT * FROM t1 WHERE col1 = (SELECT col2 FROM t2),其中SELECT * FROM t1 称为Outer Query/Outer Statement SELECT col2 FROM t2, 称为 SubQuery。
$$: SELECT goods_id, goods_name, goods_price FROM tdb_goods WHERE goods_price >= (SELECT ROUND(AVG(goods_price), 2) FROM tdb_goods);
子查询指嵌套在查询内部,且必须始终出现在圆括号内;子查询可以包含多个关键字或条件,如DISTINCY、GROUP BY、ORDER BY、LIMIT,函数等;子查询的外层查询可以是:SELECT、INSERT、UPDATE、SET或DO。
子查询返回值:子查询可以返回标量、一行、一列或子查询。
使用比较运算符的子查询:=、>, <, >=, <=, <>, !=, <=>
语法结构:operand comparision_operator subquery
用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 = '超级本');
使用 [NOT] IN 的子查询
语法结构:
operand comparison_operator [NOT] IN (subquery)
=ANY 运算符与IN等效。
!=ALL或<>ALL运算符与NOT IN 等效。
使用 [NOT] EXISTS的子查询
如果子查询返回任何行,EXISTS将返回TRUE;否则为FALSE。
多表更新
UPDATE table_references
SET col_name1 = {expr1 | DEFAULT}
[, col_name2={expr2 | DEFAULT}]...
[WHERE where_condition]
$$:UPDATE goods_tb AS gtb INNER JOIN brands_tb AS btb ON gtb.brand_name = btb.brand_name SET gtb.brand_name = brand_id;
语法结构
table_reference
{[INNER | CROSS] JOIN | {LEFT | RIGHT} [OUTER] JOIN}
table_reference
ON conditional_expr
连接类型
INNER JOIN,内连接,在MySQL中,JOIN、CROSS JOIN 和 INNER JOIN是等价的。LEFT [OUTER] JOIN,左外连接,RIGHT [OUTER] JOIN,右外连接
CREATE...SELECT
创建数据表同时将查询结果写入到数据表:
CREATE TABLE [IF NOT EXISTS] tbl_name [(create_definition, ...)] select_statement
完全复制表的结构和内容
$$:CREATE TABLE cp_goods_tb SELECT goods_id, goods_name, goods_cate, brand_name, goods_price, is_show, is_sale_off FROM goods_tb;
复制表连接:复制表
根据某一个表的某一字段创建内容类型表
$$: CREATE TABLE cates_tb( cate_id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, cate_name VARCHAR(40) ) SELECT goods_cate AS cate_name FROM goods_tb GROUP BY goods_cate;
网友评论