资源描述:
《mysql之左连接与右连接.docx》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Mysql的左连接与右连接区别1.SQLLEFTJOIN关键字LEFTJOIN关键字会从左表(table_name1)那里返回所有的行,即使在右表(table_name2)中没有匹配的行。2.SQLRIGHTJOIN关键字RIGHTJOIN关键字会右表(table_name2)那里返回所有的行,即使在左表(table_name1)中没有匹配的行。3.在Mysql中的DevDB中创建两个表CreateTabledepartmentCREATETABLE`department`(`ID`int(11)NOTNULLAUTO_INCREME
2、NT,`CODE`varchar(100)DEFAULTNULL,`NAME`varchar(200)DEFAULTNULL,PRIMARYKEY(`ID`))ENGINE=InnoDBAUTO_INCREMENT=5DEFAULTCHARSET=utf8CreateTablejobCREATETABLE`job`(`id`int(11)NOTNULLAUTO_INCREMENT,`FirstName`varchar(32)DEFAULTNULL,`LastName`varchar(32)DEFAULTNULL,`LoginName`
3、varchar(32)DEFAULTNULL,`dep_id`int(11)DEFAULTNULL,PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=5DEFAULTCHARSET=utf84.在department表和Job表中插入数据?12345insertinto`department`(`ID`,`CODE`,`NAME`)values('1','JavaR&D','JavaR&D');insertinto`department`(`ID`,`CODE`,`NAME`)values('2
4、','MysqlR&D','MysqlR&D');insertinto`department`(`ID`,`CODE`,`NAME`)values('3','InterfaceR&D','InterfaceR&D');insertinto`department`(`ID`,`CODE`,`NAME`)values('4','AndroidR&D','AndroidR&D');insertinto`department`(`ID`,`CODE`,`NAME`)values('5','IOSR&D','IOSR&D');?12345ins
5、ertinto`Job`(`id`,`FirstName`,`LastName`,`LoginName`,`dep_id`)values('1','Peter','Qiu','Qiu','1');insertinto`Job`(`id`,`FirstName`,`LastName`,`LoginName`,`dep_id`)values('2','Tom','Lee','Lee','2');insertinto`Job`(`id`,`FirstName`,`LastName`,`LoginName`,`dep_id`)values('
6、3','Garfield','Wang','Wang','3');insertinto`Job`(`id`,`FirstName`,`LastName`,`LoginName`,`dep_id`)values('4','哆啦A梦','Jone','Jone',NULL);insertinto`Job`(`id`,`FirstName`,`LastName`,`LoginName`,`dep_id`)values('5','Westlife','西城男孩','Westlife','8');department表数据IDCODENAME1
7、JavaR&DJavaR&D2MysqlR&DMysqlR&D3InterfaceR&DInterfaceR&D4AndroidR&DAndroidR&D5IOSR&DIOSR&DJob表数据idFirstNameLastNameLoginNamedep_id1PeterQiuQiu12TomLeeLee23GarfieldWangWang34哆啦A梦JoneJone(NULL)5Westlife西城男孩Westlife85.以Job表进行左连接(leftjoin)?123/*以Job表进行左连接,此时数据主要以Job表为主,关联de
8、partment表,如果Job的dep_id为null或者在department表中无对应的Id匹配对应的字段自动填充null*/SELECT*FROMJobtable_name1LEFTJOINdepartmentta