1.子查询,出现在其他SQL语句的SELECT子句
SELECT * FROM t1 WHERE col1=(SELECT col2 FROM t2);
第一个SELECT称为外层查询,第二个称为子查询,嵌套在内部的查询。称为子查询。可以包含多个关键字或条件
DISTINCT,GROUP BY.ORDER BY,LIMIT,函数等。子查询可以返回值可以是标量,一行,一列或子查询。
外层查询可以是SELECT,INSERT,UPDATE,SET或DO
(1).比较运算符的子查询。
=,>,<,>=,<=,<>,!=,<=>
SELECT * FROM t1 WHERE price>=(SELECT AVG(price) t1 )
(2).ANY SOME ALL子查询在返回多个结果时可用修饰
(3).IN的子查询
SELECT * FROM t1 WHERE price IN (SELECT * FROM t1 WHERE price>5000)
2.INSET.....SELECT插入
INSET t1(cate_names) SELECT goods_cate FROM tdb_goods_cate GROUP BY goods_cate
3.多表的更新
UPDATE table_references SET col_name1={expr1|DEFAULT} [,col_name2={expr2|DEFAULT}]..[WHERE where_condition]
UPDATE tdb_goods INNER JOIN tdb_goods_cates ON goods_cate= cate_name SET goods_cate=cate_id;
4.多表更新一步到位
CREATE TABLE tdb_goods_brands( brand_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, brand_name VARCHAR(40) NOT NULL ) SELECT brand_name FROM tdb_goods GROUP BY brand_name;
5.连接,mysql在SELECT语句,多表更新,多表删除语句中支持JOIN操作。有相同字段的名字,起别名
(1).内连接 INNER JOIN。仅显示符合连接的记录。
使用ON关键字来设定连接条件,也可用WHERE来代替
SELECT goods_id,goods_name FROM tdb_goods t INNER JOIN tdb_goods_cate g ON t.cate_id= g.cate_id
(2).左外连接,显示左边的全部记录及右表符合连接条件的记录
SELECT goods_id,goods_name FROM tdb_goods t LEFT JOIN tdb_goods_cate g ON t.cate_id= g.cate_id
(3).右外连接,显示右表的全部记录及左表符合连接条件的记录
SELECT goods_id,goods_name FROM tdb_goods t RIGHT JOIN tdb_goods_cate g ON t.cate_id= g.cate_id
6.多表连接
SELECT goods_id,goods_name,cate_name,brand_name FROM tdb_goods g INNER JOIN tdb_goods_cates c ON g.cate_id=c. cate_id INNER JOIN tdb_goods_brands b ON g.brand_id=b.brand_id
7.自连接,顾名思义自己连接自己
数据准备
INSERT tdb_goods_types(type_name,parent_id) VALUES('家用电器',DEFAULT); INSERT tdb_goods_types(type_name,parent_id) VALUES('电脑、办公',DEFAULT); INSERT tdb_goods_types(type_name,parent_id) VALUES('大家电',1); INSERT tdb_goods_types(type_name,parent_id) VALUES('生活电器',1); INSERT tdb_goods_types(type_name,parent_id) VALUES('平板电视',3); INSERT tdb_goods_types(type_name,parent_id) VALUES('空调',3); INSERT tdb_goods_types(type_name,parent_id) VALUES('电风扇',4); INSERT tdb_goods_types(type_name,parent_id) VALUES('饮水机',4); INSERT tdb_goods_types(type_name,parent_id) VALUES('电脑整机',2); INSERT tdb_goods_types(type_name,parent_id) VALUES('电脑配件',2); INSERT tdb_goods_types(type_name,parent_id) VALUES('笔记本',9); INSERT tdb_goods_types(type_name,parent_id) VALUES('超级本',9); INSERT tdb_goods_types(type_name,parent_id) VALUES('游戏本',9); INSERT tdb_goods_types(type_name,parent_id) VALUES('CPU',10); INSERT tdb_goods_types(type_name,parent_id) VALUES('主机',10);
SELECT s.type_id,s.type_name,t.type_name FROM tdb_goods_types s LEFT JOIN tdb_goods_types t ON s.parent_id=t.type_id;
8.多表删除
DELETE t1 FROM tdb_goods t1 LEFT JOIN (SELECT goods_id,goods_name FROM tdb_goods GROUP BY goods_name HAVING count(goods_name)>=2) t2 ON t1.goods_name=t2.goods_name WHERE t1.goods_id>t2.goods_id