您的位置:首页 > 数据库 > MySQL

SQL左连接攻略--Mysql学习心得(符合sql标准)

2007-08-24 11:41 666 查看
SQL左外连接:明白左连接也就明白了右连接

两表外连接

出货表
客户id、客户名称、产品id、产品数量、备注

create table a_prod_out
(
custom_id int not null,
custom_name varchar(200) not null,
prod_id int default 0 null,
prod_num int default 0 null,
remark varchar(500) null,
constraint pk_a_prod_out primary key (custom_id)
)

产品表
产品id、产品名称、生产厂家

create table b_prod
(
prod_id int not null,
prod_name varchar(200) not null,
manufacturer_id int default 0 null,
remark varchar(500) null,
constraint pk_b_prod primary key (prod_id)
)

左连接
左连接以左表为标准,并接右边的部分数据,并接条件即产品id
此时左表信息全部显示,对应连接右边中符合并接条件的数据

select a.custom_id,a.custom_name,b.prod_name,b.manufacturer_id
from a_prod_out a left outer join b_prod b
on a.prod_id = b.prod_id ;

三表外连接

厂商表 客户对应用什么产品
create table a_mfter
(
manufacturer_id int not null,
manufacturer_name varchar(200) not null,
constraint pk_a_mfter primary key (manufacturer_id)
)

select a.custom_id,a.custom_name,b.prod_name,c.manufacturer_name
from a_prod_out a
left outer join b_prod b
on a.prod_id = b.prod_id
left outer join a_mfter c
on b.manufacturer_id = c.manufacturer_id;

SQL结果同样是以左表出货表为标准,并接产品表和厂商表
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: