码迷,mamicode.com
首页 > 其他好文 > 详细

多表操作

时间:2015-09-12 00:45:55      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

多表操作

多表操作

Table of Contents

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;

多表操作

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4802420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!