例如:
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 round(avg(goods_price), 2) from tdb_goods;
列出所有商品价格在平均价格之上的商品
select goods_id,goods_name,goods_price from tdb_goods
where goods_price >= (select round(avg(goods_price),2) from tdb_goods);
用 SOME(任意一个),ANY(任意一个),ALL(所有的) 修饰比较运算符
= ANY运算符 与IN 等效,!=ALL或<>ALL与NOT IN 等效;
如果子查询返回任何行,EXIST将返回TRUE,否则返回false;
在一个数据表的分类中,可能存在大量重复的数据,这时候可以奖建立两个数据表关联,提高查询效率。
实例
将查询结果写入数据表
Insert tdb_goods_cates(cate_name) select goods_cate from tdb_goods group by goods_cate;
多表的更新基本上与单表更新相似。
连接类型
INNER JOIN(与JOIN,CROSS JOIN等价) 内连接,
LEFT[OUTER] JOIN 左外连接
RIGHT[OUTER] JOIN 右外连接
SQL语句实例
update tdb_goods inner join tdb_goods_cates on goods_cate = cate_name set goods_cate = cate_id;
SQL语句实例
(1)
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;
(2) 当两个表的字段名相同时,可以为两个表分别起一个别名,例如下面的g和b:
update tdb_goods as g inner join tdb_goods_brands as b on g.brand_name = b.brand_name set g.brand_name = b.brand_id;
(3)修改表的结构
alter table tdb_goods change goods_cate cate_id smallint unsigned not null,change brand_name brand_id smallint unsigned not null;
通常使用 ON 关键字来设定连接条件,使用WHERE关键字进行结果集记录的过滤。
内连接:显示左表及右表符合条件的记录(交集)。
SQL语句实例
select goods_id,goods_name,cate_name from tdb_goods inner join tdb_goods_cates on tdb_goods.cate_id =tdb_goods_cates.cate_id;
(1) 左外连接: 显示左表中的全部和右表中符合条件的部分。
select goods_id,goods_name,cate_name from tdb_goods left join tdb_goods_cates on tdb_goods.cate_id = tdb_goods_cates.cate_id;
(2) 右外连接: 显示右表中的全部和左表中符合条件的部分。
select goods_id,goods_name,cate_name from tdb_goods right join tdb_goods_cates on tdb_goods.cate_id =tdb_goods_cates.cate_id;
select goods_id,goods_name,cate_name,brand_name,goods_price from tdb_goods as g
inner join tdb_goods_cates as c on g.cate_id = c.cate_id
inner join tdb_goods_brands as b on g.brand_id = b.brand_id\G;