多表操作
drop table if exists one;
create table one (
id int,
name varchar(30)
);
drop table if exists two;
create table two (
id int,
name varchar(30)
);
create table thr (
name1 varchar(30),
name2 varchar(30)
);
insert into one (id, name) values
(1, ‘one_1‘),
(2, ‘one_2‘),
(3, ‘one_3‘);
insert into two (id, name) values
(1, ‘two_1‘),
(2, ‘two_2‘),
(3, ‘two_3‘),
(4, ‘two_4‘);
insert into thr (name1, name2) values
(‘two_1‘, ‘thr_1‘),
(‘two_2‘, ‘thr_2‘);
| id | name |
+------+-------+
| 1 | one_1 |
| 2 | one_2 |
| 3 | one_3 |
| id | name |
+------+-------+
| 1 | two_1 |
| 2 | two_2 |
| 3 | two_3 |
| 4 | two_4 |
| name1 | name2 |
+-------+-------+
| two_1 | thr_1 |
| two_2 | thr_2 |
select one.*, two.* from one left join two on one.id = two.id;
select two.*, one.* from two left join one on one.id = two.id;
-- 上面两条语句的美化版
select one.id as id1, one.name as name1, two.id as id2, two.name as name2 from one left join two on one.id = two.id;
select two.id as id2, two.name as name2, one.id as id1, one.name as name1 from two left join one on one.id = two.id;
select one.*, two.*, thr.* from one left join two on one.id = two.id left join thr on two.name = thr.name1;
select one.id as id1, one.name as name1, two.id as id2, two.name as name2, thr.name1 as name3 from one left join two on one.id = two.id left join thr on two.name = thr.name1;
update one left join two on one.id = two.id set one.id = 10, two.id = 10 where one.id = 1; -- 通过 set 后面的来修改
-- 两个表的数据都被修改了
select * from one;
select * from two;
delete from one using one left join two on one.id = two.id where one.id = 10; -- 只删除了 one 表 id 为 10 的行
select * from one;
select * from two;
-- 同时删除两个表
-- delete from one, two using one left join two on one.id = two.id where one.id = 10;