MySQL高级查询

高级查询

1.子查询

⼦查询嵌⼊到其他查询语句中查询语句,⼦查询只能出现在from,where、having中。
⼦查询不要⽤select *,exists除外。

select title
from forum
where uid in (select id from php_user where name='王琨' );
select * from blog_article where cid in 
(select cid from blog_category where name='⼼情');
select * from (select uid,username,gender from blog_user wheregender='男') as user;

2.多表查询

多表连接必须要有连接条件,否则结果没有意义。
多表连接有两种写法:隐式(标准sql)和显式内连接。
隐式(标准sql)连接:连接条件写到where字句中。例如,

select title,content,name,publish_time from user u,foru	m f  # 给表起⼀个别名,⽅便书写
where u.id = f.uid;  # 在where写链接条件
select title,content,name,publish_timefrom user u,forum f
where u.id = f.uid and name='王琨';

显式内连接(inner join)。例如,

select a.uid,username,title,content
from bbs_user a inner join bbs_forum b on a.uid =b.uid  # 关联条件
where a.uid < 5;  # 过滤条件
select username,name,title
from bbs_user a inner join bbs_forum c on c.uid =a.uid
inner join bbs_category b on c.cid = b.cid;

表的⾃身可以与自身连接。例如,

select * from areainfo a,areainfo b where a.pid=b.code anda.name='⻘河县';

3.外连接

两张表关联查询时,根据以那种表为主可以分为左外连接和右外连接。

左外连接以左表为主,如果右边的表⾥没有匹配的记录,则添加⼀个万能记录(各个字段都为null)与之连接。

select username,r.* from blog_user u left join  blog_remark r onu.uid = r.uid

右外连接(right join)与左外连接类似,以右表为主,如果左边的表⾥没有匹配记录,则增加⼀个万能记录与之连接。

4.集合操作

可以使⽤union将两个查询结果合并,mysql只⽀持并,不⽀持差和交。两个结果集中字段数⼀样,对应字段类型兼容。

注意:⾃动去除重复记录,不去除重复记录可以⽤union all;
order by放到最后。

select * from student where class = '95031'
union all
select * from student where ssex='⼥';

5.内部函数

字符串函数。
在这里插入图片描述
日期函数。
在这里插入图片描述
数学函数。
在这里插入图片描述
其他函数。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值