/*表結(jié)構(gòu)及數(shù)據(jù)*/
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` varchar(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `test` VALUES ('1', '張三', '18', '男');
INSERT INTO `test` VALUES ('2', '李四', '20', '女');
INSERT INTO `test` VALUES ('3', '王五', '32', '男');
/*--------------------------*/
CREATE TABLE `demo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) DEFAULT NULL,
`change` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `demo` VALUES ('1', '2', '15');
INSERT INTO `demo` VALUES ('2', '3', '58');
INSERT INTO `demo` VALUES ('3', '2', '16');
情況1:on條件是1=1
sql
/*當(dāng)on的條件是1=1的時(shí)候,inner join和left join的結(jié)果是一致的*/
select * from test left join demo on 1 = 1;
select * from test inner join demo on 1 = 1
結(jié)果:(條數(shù)是:3*3=9條)

查詢結(jié)果圖
情況2:添加實(shí)際的on條件,一個(gè)on條件,left join方式
/**
在情況1的基礎(chǔ)上,挨個(gè)判斷是否滿足on的條件,如果滿足則保留
如果不滿足,則左表保留一條記錄,右表的記錄為null
**/
select * from test left join demo on test.id = demo.uid;

left join 一個(gè)on條件
情況3:添加實(shí)際的on條件,一個(gè)on條件,inner join方式
/**
在情況1的基礎(chǔ)上,挨個(gè)判斷是否滿足on的條件,如果滿足則保留,如果不滿足,則丟棄
**/
select * from test inner join demo on test.id = demo.uid;

inner join 一個(gè)on條件
情況4:添加實(shí)際的on條件,兩個(gè)on條件,left join方式
/**
在情況1的基礎(chǔ)上,挨個(gè)判斷是否同時(shí)滿足on的所有條件,如果滿足則保留
如果不滿足,則左表保留一條記錄,右表的記錄為null
**/
select * from test left join demo on test.id = demo.uid and test.id > 2;

left join 兩個(gè)on條件
情況5:添加實(shí)際的on條件,兩個(gè)on條件,inner join方式
/**
在情況1的基礎(chǔ)上,挨個(gè)判斷是否同時(shí)滿足on的所有條件,如果滿足則保留
如果不滿足,則丟棄
**/
select * from test inner join demo on test.id = demo.uid and test.id > 2;

inner join 兩個(gè)on條件