SQL连接多表
SQL连接多表内连接使用 where 完成多表的连接使用 cross join 得到 两个表的笛卡尔乘积使用 内连接 xxx inner join xxx on 条件连接两个以上的表外连接自连接汇总函数 + 多表连接内连接因为要在不同的表中查询数据。在查询的过程中需要指定按照哪个维度来进行查询(即,按照哪个列,或者哪几个列对数据进行拼接和查询)使用 where 完成多表的连接举例1: 在商品表和销
·
SQL连接多表
内连接
因为要在不同的表中查询数据。在查询的过程中需要指定按照哪个维度来进行查询(即,按照哪个列,或者哪几个列对数据进行拼接和查询)
使用 where 完成多表的连接
举例1: 在商品表和销售表中,找出两者id相同的商品。== 找出商品表和销售表中的商品类型和销售价格
select
product_type,
sale_price
from
product, shopproduct
where
product.product_id = shopproduct.product_id;
运行结果
同时也可以指定表的名称 ,举例:
select
product_type,
sale_price
from
product p, shopproduct s
where
p.product_id = s.product_id;
注意: 如果不指定where的限制条件,那么就返回两个表的笛卡尔乘机。
使用 cross join 得到 两个表的笛卡尔乘积
select
product_type,
sale_price
from
product cross join shopproduct;
使用 内连接 xxx inner join xxx on 条件
select
product_type,
sale_price
from
product inner join shopproduct
on product.product_id = shopproduct.product_id;
注意, 也可以使用 join 直接完成连接
select
product_type,
sale_price
from
product join shopproduct
on product.product_id = shopproduct.product_id;
连接两个以上的表
举例:查询某个客户购买了哪些商品 ?
select
p.product_name ## 商品名称
from
customers c
join orders o on c.cust_id = o.cust_id
join orderitems oi on oi.order_num = o.order_num
join products p on p.product_id = oi.product_id
where
c.cust_name = 'The toy store'; ## 用户名称
外连接
查询没有关联到的记录,可以使用外连接
- left outer join == left join
- right outer join == right join
举例 :查询没有订单的客户id
select
distinct c.cust_id
from
customer c
left outer join orders o on c.cust_id = o.cust_id
where
o.cust_id is null
;
自连接
场景:某个供应商在不同国家中使用的名称
方法1 :自连接(推荐使用)
select
distinct v1.vend_name
from
vendors v1, vendors v2
where
v1.vend_country = v2.vend_country
and v2.vend_name = '供应商1名称'
;
方法2 :子查询
select
distinct vend_name
from
vendors
where
vend_country = (
select
distinct vend_country
from
vendors
where
vend_name='供应商1名称'
)
;
汇总函数 + 多表连接
多个表中,每个顾客的订单数
select
c.cust_name, count(distinct o.order_name)
from
customers c
join orders o on c.cust_id = o.cust_id
group by
c.cust_name
;
查询多个表中的,每个顾客订购的商品总金额
select
c.cust_name, sum(o.quantity)
from
customers c
join orders o on c.cust_id = o.cust_id
join orderitems oi on oi.order_num = o.order_num
group by
c.cust_name
;
更多推荐
已为社区贡献7条内容
所有评论(0)