mysql的连接查询

1.图示各种连接:

INNER JOIN(JOIN):

mysql的连接查询_第1张图片

LEFT JOIN:

mysql的连接查询_第2张图片

RIGHT JOIN:
mysql的连接查询_第3张图片

2.使用案例
创建a\_table和b\_table,并插入测试数据
CREATE TABLE `a_table` (
  `a_id` int(11) DEFAULT NULL,
  `a_name` varchar(10) DEFAULT NULL,
  `a_part` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into a_table values(
1,'老潘','总裁部');
insert into a_table values(
2,'老王','秘书部');
insert into a_table values(
3,'老张','设计部');
insert into a_table values(
4,'老李','运行部');

CREATE TABLE `b_table` (
  `b_id` int(11) DEFAULT NULL,
  `b_name` varchar(10) DEFAULT NULL,
  `b_part` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into b_table values(
2,'老王','秘书部');
insert into b_table values(
3,'老张','设计部');
insert into b_table values(
5,'老刘','人事部');
insert into b_table values(
6,'老黄','生产部');
insert into b_table values(
7,'老张','测试部');
各种连接测试的sql脚本:
-- left join
left join select a.a_name,a.a_part,b.b_name,b.b_part from a_table a 
left join b_table b on a.a_id = b.b_id;
-- 主表与左连接表中若有1:n的连接,选取左连接表中最大的id进行左连接查询
select a.a_name,a.a_part,b.b_name,b.b_part
from a_table a
left join(
    select * from b_table t1 
    join (select max(b_id) as id from b_table group by b_name ) t2 on t1.b_id = t2.id
)b on a.a_name = b.b_name;
-- inner join 
select a.a_name,a.a_part,b.b_name,b.b_part
from a_table a
inner join b_table b on a.a_id = b.b_id;
-- right join
select a.a_name,a.a_part,b.b_name,b.b_part
from a_table a
right join b_table b on a.a_id = b.b_id;

以上参考自:https://blog.csdn.net/plg17/article/details/78758593
https://blog.csdn.net/J\_\_Max/article/details/87453024

你可能感兴趣的:(mysql)