SQL——连接查询

以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后面的条件,把符合条件的右表的数据附加到左表

2.右连接查询:

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

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

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  

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

逃避不一定躲得过,面对不一定最难过
原文地址:https://www.cnblogs.com/yangzhenlong/p/3809619.html