目 录CONTENT

文章目录

SQL高级语法(一)

Rain
2020-05-18 / 0 评论 / 0 点赞 / 400 阅读 / 3,011 字 / 正在检测是否收录...

一、Top

Top子句用于返回要返回的记录的数目,但并不是所有的数据库都支持top子句

1:SQL Server

Select top 5 * from user

2:MySQL

Select * from user limit 5

3:Oracle

Select * from user where ROWNUM <= 5

二、Like

User表的初始数据如下

1:找出以li开头的数据

Select * from user where user_name like 'li%'

2:找出以ry结尾的数据

Select * from user where user_name like '%ry'

3:找出含有a的数据

Select * from user where user_name like '%a%'

4:找出第二个字母是a第四个字母是y的数据

Select * from user where user_name like '_a_y'

三、通配符

在搜索数据库中的数据的时候SQL通配符可以替代一个或多个字符。SQL通配符必须与like运算符一起使用

1: _ 替代一个字符

找出第二个字母是a第四个字母是y的数据

Select * from user where user_name like '_a_y'

2: % 替代一个或多个字符

找出以ry结尾的数据

Select * from user where user_name like '%ry'

3: [] 字符列中的任意一个单字符

找出以a或者l开头的数据

Select * from user where user_name like '[al]%'

找出不是a或者l开头的数据

Select * from user where user_name like '[!al]%'

四、In

只要数据满足in里面的一个条件就可以了

找到user_age是12或者13的数据

Select * from user where user_age in (12,13)

找到user_name是Harry和Mary的数据

Select * from user where user_name IN ('mary','harry')

五、Between

选取两个值之间的数据

查询年龄在12和14之间的数据

Select * from user where user_age between 12 and 14

查询字母在Alice和John之间的数据

Select * from user where user_name between 'alice' AND'john'

六、Aliases

指定别名

假设我们有两个表分别是user和Room 。我们分别指定他们为u和r。

1:不使用别名

Select room.room_name,user.user_name,user.user_age from user ,room  Where user.user_age=12 and room.room_id = 1

2:使用别名

使用别名的时候直接将别名跟在后面,不使用as也可以

Select r.room_name,u.user_name,u.user_age from user as u,room as r  Where u.user_age=12 and r.room_id = 1

七、Join

数据库中的表可以通过键将彼此联系起来,主键是一个列,在这个列中的每一行的值都是唯一的,在表中,每个主键的值都是唯一的,这样就可以在不重复每个表中的所有数据的情况下,把表间的数据交叉捆绑在一起。

以下为表user和表Room的数据

1:引用两个表

找出在Room of boy相关联的用户信息

Select u.user_name,u.user_age,r.room_name from user as u,room as r 

Where u.room_id = r.room_id and r.room_name='room of boy'

2:使用关键字join来连接两张表

Select u.user_name,u.user_age,r.room_name

from user as u

join room as r

on u.room_id = r.room_id and r.room_name='room of boy'

八、Inner join

Inner join 与 join 用法一致

Select u.user_name,u.user_age,r.room_name

from user as u

inner join room as r

on u.room_id = r.room_id and r.room_name='room of boy'

九、Left join

注意:左连接以左边的表为主体,也就是说会列出左边的表中的所有的数据,无论它是否满足条件。

1:user在左边

Select u.user_name,u.user_age,r.room_name

from user as u

Left join room as r

on u.room_id = r.room_id and r.room_name='room of boy'

2:Room在左边

Select u.user_name,u.user_age,r.room_name

From room as r

Left join user as u

on u.room_id = r.room_id and r.room_name='room of boy'

十、Right join

注意:右连接以右边的表为主体,也就是说会列出右边的表中的所有的数据,无论它是否满足条件。

1:Room在右边

Select u.user_name,u.user_age,r.room_name

from user as u

Right join room as r

on u.room_id = r.room_id and r.room_name='room of boy'

2:user在右边

Select u.user_name,u.user_age,r.room_name

from  room as r

Right join user as u

on u.room_id = r.room_id and r.room_name='room of boy'
0

评论区