MySQL基础_多表查询

1.简单多表查询

select * from [表名1],[表名2]
select * from product,productdir

2.笛卡尔积:没有连接条件的表的关系返回的结果。

                    多表查询会产生笛卡尔积。如下图

 正常数据

3.隐式内连接查询

-- 查询货品ID ,货品名称,货品所属分类
select productId,productName,dirName from product,productdir 
where product.dirId=productdir.dirId        -- 重复列名使用  [表名].[列名]

select productId,productName,dirName from product p,productdir pd
where p.dirId=pd.dirId        -- 表定义别名

-- 查询货品ID ,货品名称,货品所属分类
select productId,productName,dirName from product,productdir where product.dirId=productdir.dirId

select productId,productName,dirName from product p,productdir pd where p.dirId=pd.dirId
-- 查询零售价格大于200的无线鼠标
-- 查询零售价格大于200的无线鼠标(别名)
select * from product p,productdir pd where  p.dirId=pd.dirId and p.salePrice>200 
and  pd.dirName ='无线鼠标'

-- 查询每个货品对应的分类以及对应的库存
select productName,dirName,stockNum from product p,productdir pd,productstock ps
where p.dirId=pd.dirId and p.productId=ps.product_id

-- 如果库存货物都销售完成,按照利润从高到底查询货物名称,零售价,货品分类(三张表)
select productName,salePrice,dirName,stockNum*(salePrice-costPrice) as profit 
from product p,productdir pd,productstock ps where p.dirId=pd.dirId and p.productId=ps.product_id 
order by  profit desc 

4.自连接查询

    自连接查询:把一张表看成两张表使用

select b.dirId, b.dirName,a.dirName from productdir a,productdir b
where a.dirId=b.parent_id

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值