示例:selectarticle.* from article inner join user on article.uid=user.uid
4. mysql循环
4.1while…end while循环
Create procedure p1()
begin
declare v int;
set v=0;
while v<5 do
insertinto t values(v)
setv=v+1;
end while;
end;
4.2repeat…end repeat循环
create procedure p2()
begin
declare v int;
set v=0;
repeat
insert into t values(v);
set v=v+1;
until v>=5;
end repeat;
end;
注:until后面可以没有分号
4.3loop…end loop循环
create procedure p3()
begin
declare v int;
set v=0;
loop_label:loop
insert into tvalues(v);
set v=v+1;
if v>=5 then
leaveloop_label;
end if;
end loop;
end;
5. mysql视图查询
5.1视图定义
视图是由查询结果形成的一张虚拟表。
5.2视图的使用
如果某个查询结果出现的非常频繁,也就是要经常拿这个查询结果来做子查询
5.3语法
create view 视图名 as select 语句
5.4视图优点
l 简化查询语句
示例:有一张商品表,我们要经常查每个栏目下的商品的平均价格
Select cat_id, avg(shop_price) from goods group by cat_id;
创建一个视图
create view avgPrice as select cat_id, avg(shop_price) fromgoods group by cat_id;
当我们再次查询每个栏目平均价格时,只需要这么写
select * from avgPrice;
l 进行权限控制
把表的权限封闭,但是开放相应的视图权限,视图里只开放部分数据列,例如我们的goods商品表,我们不想让别人看到我们的销售价格,这个时候我们可以把商品表权限封闭,创建一张视图
create view showGoods as select goods_id,goods_name fromgoods;
5.5视图修改
Alter view 视图名 as select 语句;
5.6视图与表的关系
视图是表的查询结果,自然表的数据变了,会影响视图的结果
6. mysql关联查询
6.1连接查询简介
连接查询中用来连接两个表的条件称为连接条件或连接谓词。其形式为:
[<表1>].<列名><连接运算符>[<表2>].<列2>
常见连接运算符包括
l 比较运算符:=、>、<、>=、<=、!=、between和and
l 逻辑运算符:not、and、or
6.2连接按照结果集分类
l 内连接:表中的行互相连接,结果集的行数等于每个表满足条件的行数乘积,参与连接的表示平等的。
l 外连接:参与连接的表有主次之分,主表的每一行数据去匹配从表的数据列,符合连接条件的数据直接返回到结果集中,不符合连接条件的的数据列将以null填充后返回到结果集中,其中外连接又分为左外连接,右外连接和全连接。
6.3内连接查询
内连接语法结构:
Select <属性或表达式列表> from <表名> [inner]join <表名> on <连接条件> [where <限定条件>]
Inner可以省略,当只见到join时就是省略掉了inner。内连接就是传统的连接操作,这里用on子句指定连接条件,用where指定其他限定条件,
示例:select p.name,c.countryname from country as c inner join person p onp.countryid=c.countryid
6.4左外连接查询
左外连接语法结构:
Select <属性或表达式列表> from <表名> leftouter join <表名> on <连接条件> [where <限定条件>]
左外连接在结果表中包含第一个表中满足条件的所有记录,如果连接条件匹配,第二张表返回相应的值,否则返回null。也就是说不管第二个表有没有记录,第一张表的字段都会返回。
示例:select p.name,c.countryname from country as c right join person p onp.countryid=c.countryid
6.5右外连接查询
右外连接查询语法结构:
Select <属性或表达式列表> from <表名> rightouter join <表名> on <连接条件> [where <限定条件>]
右外连接的结果表中包含第二张表中满足条件的所有记录,如果连接条件匹配,第一张表返回相应的值,否则返回null。
示例:select p.name, c.countryname from country as c right join person pon p.countryid=c.countryid
6.6全外连接查询
全外连接查询语法结构:
Select <属性或表达式列表> from <表名> fullouter join <表名> on <连接条件> [where <限定条件>]
全外连接查询的结果集表中包含两个表满足记录所有记录。如果在连接上条件上匹配的元组,则另一个表返回相应的值,否则返回null