MySQL——多表查询与子查询

进行多表查询与子查询的综合练习

多表查询与子查询可以建立连接,用子查询可解决的问题使用多表查询同样可以达到目的

代码验证:

#-----多表关联查询----
#查询所有用户的订单
#分析:将用户表与订单表用以内连接的方式根据用户的userId连接起来合并查询
select * from user u INNER JOIN orders o on u.userId=o.userId;
#查询用户id为 1 的所有订单详情
#方式1:内连接方式
#分析:根据上面的内连接方式,之后增加where条件得出id=1的用户订单,在连接订单详情表,查出用户订单详情
select * from user u INNER JOIN orders o on u.userId=o.userId where u.userId=1;
select * from user u INNER JOIN orders o on u.userId=o.userId INNER JOIN orderitem m on o.oid=m.oid where u.userId=1;
#------子查询------
#查看用户为张三的订单
#分析:单行单列的子查询,先查询username为'张三'的userI为多少,之后以userId为标准到orders表中查询订单信息
select userId from user where username='张三';
#组合
select * from orders where userId=(select userId from user where username='张三');
#方式2:使用多表查询的方式也可以达到和子查询一样的效果
select * from user u INNER JOIN orders o on u.userId=o.userId where u.username='张三';
#查询出订单的价格大于800的所有用户信息
#分析:在订单表中查询出价格大于800的userId,以此为连接查询用户信息
select userId from orders where totalprice>800;
#组合:这是多行单列的形式采用枚举in的方式,此外还有all和any的方式
select * from user where userId in(select userId from orders where totalprice>800);
#方式:多表查询
select * from user u INNER JOIN orders o on u.userId=o.userId  where o.totalprice>800;
#结论:多表查询与子查询是相通的
#查询所有订单信息,每页显示5条数据,请查询出第6页的数据
select * from orders LIMIT 0,5;

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值