所用数据表:用户,钱包,订单
一、from子查询
--查询钱包里金额大于30000 select * from Users where exists (select User_ID from Wallets where Money > 30000 and User_ID = Users.ID) select * from Users where ID in (select User_ID from Wallets where Money > 30000)
二、链接查询
内连接(inner join)外连接(left/right/full outer join)交叉链接(coress join)
1. 内连接
分为显式链接和隐式链接的,返回连接表中符合连接条件和查询条件的数据行
显示:表 inner join 表 on 链接条件
select * from Users inner join Wallets on Users.ID = Wallets.User_ID where Money > 30000
隐式:from 表1,表2 on 链接条件
select * from Wallets,Users where Wallets.User_ID=Users.ID and Money > 10000
2. 外连接
a. 左链接:以左边为基准,全部查询右边没有匹配的值显示为空
--用户ID为3,4,5的没有钱包数据 select * from Users left outer join Wallets on Users.ID = Wallets.User_ID
b. 右链接:和左连接相反,以右边为基准左边表的字段为空
select * from Wallets right outer join Users on Users.ID = Wallets.User_ID
c. 全链接:左右全部连接没有对应值得字段为空
select * from Users full outer join Wallets on Users.ID = Wallets.User_ID where User_ID is null or Users.ID is null
3. 交叉链接:表1的每一行记录都会连接表2的每一行记录
--等于User表* Wallet表(笛卡儿积) select * from Users cross join Wallets where Users.ID = 3