创建表(Create table):
CREATE TABLE A ( Id INT PRIMARY KEY, Name VARCHAR(20) NOT NULL); CREATE TABLE B ( Id INT PRIMARY KEY, Name VARCHAR(20) NOT NULL); |
插入数据(Insert data):
insert into A(id,name) values(1,'Mary1'); insert into A(id,name) values(2,'Mary2'); insert into A(id,name) values(3,'Mary3'); |
insert into B(id,name) values(1,'Tom1'); insert into B(id,name) values(2,'Tom2'); insert into B(id,name) values(4,'Tom4'); |
查询a表(Select from a):
Select * from a; |
查询b表(Select from b):
Select * from b; |
内连接(Inner join,自然连接): 内连接只有两个表数据完全匹配才显示查询结果(个人觉得,和不用没什么区别)
Select a.*,b.* from a inner join b where a.id = b.id; |
Select a.*, b.* from a, b where a.id = b.id; |
左连接(Left join): 显示左表所有数据,只有右表数据和左表匹配是才显示右表数据,如果左表数据在右表中没有匹配的行,用null显示(如下,id = 3)
Select a.*,b.* from a left join b on a.id = b.id; |
右连接(Right join): 显示右表所有数据,只有左表数据和右表匹配时,才显示左表数据,如果右表数据在左表中没有匹配的行,用null显示(如下,id=4),跟左连接相反
Select a.*,b.* from a right join b on a.id=b.id; |