您的位置:首页 > 博客中心 > 数据库 >

SQL——连接查询

时间:2022-03-10 17:46

以mysql为例:


新建两张表table1和table2

CREATE TABLE `table1` (
   `id` int(11) NOT NULL auto_increment,
   `name` varchar(20) default NULL,
   PRIMARY KEY  (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf-8
CREATE TABLE `table2` (
   `id` int(11) NOT NULL auto_increment,
   `name` varchar(20) default NULL,
   PRIMARY KEY  (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf-8

插入数据

table1
id name
1 11
2 111
3 1111
4 11111
table2
id name
1 22
2 222
3 2222

 


1.左连接查询:

 

SELECT * FROM table1 t1 
    LEFT JOIN table2 t2
    ON t1.id=t2.id

 

理解:先把左表的所有数据查出来,再根据on后面的条件,把符合条件的右表的数据附加到左表

gxlsystem.com,布布扣

 

 

 

2.右连接查询:

SELECT * FROM table1 t1  RIGHT JOIN table2 t2 ON t1.id=t2.id

理解:先把右表的所有数据查出来,再根据on后面的条件,把符合条件的左表的数据附加到右表

gxlsystem.com,布布扣

3.内连接查询

SELECT * FROM  table1 a  JOIN table2 b ON a.id=b.id  
或者
SELECT * FROM  table1 a INNER JOIN table2 b ON a.id=b.id  
或者
SELECT * FROM  table1 a , table2 b WHERE a.id=b.id  

理解:以上三条语句同等,即把符合相同条件的表的数据查出来

gxlsystem.com,布布扣

SQL——连接查询,布布扣,bubuko.com

热门排行

今日推荐

热门手游