MySQL连表操作

MySQL连表

返回首页

连表操作

使userinfo表的part_id列与department的id关联

select * from userinfo,department where userinfo.part_id = department.id

 

推荐的连表方式 left/right join(连接,左连接/右连接,join是连接,left是从左边连,right是从右边连)

select * from userinfo left join department on userinfo.part_id = department.id

left是左边的userinfo表的全部显示,意味着department表中如果没有和userinfo相关的就不会被显示出来

 

select * from userinfo right join department on userinfo.part_id = department.id

right是右边的department表的全部显示,意味着userinfo表中如果没有和department相关的就不会被显示出来

 

innder方法,如果连表有一部分是null的就会给隐藏。

select * from userinfo innder join department on userinfo.part_id = department.id
userinfo表中没有和department表中相对应的值,会出现null,而innder方法将出现null时一行隐藏


统计表中某列的个数,用count统计。

select count(id) from userinfo;

 

关联多个表

select * from

  userinfo

  left join department on userinfo.part_id = department.id

  left join department1 on userinfo.part_id = department.id

  left join department2 on userinfo.part_id = department.id

  left join department3 on userinfo.part_id = department.id

 前提是表和表之间是有关系

  

例如:

  select  score.sid, student.sid  from  score

    left join student on score.student_id = student.sid

    left join course on score.course_id = course.cid

    left join class on student.class_id = class.cid

    left join teacher on course.teacher_id=teacher.tid

 

select score_id,stu_id from score

  left join student on score.stu_id = student.student_id

  left join course on score.cou_id = course.course_id

  left join class on student.cla_id = class.class_id

  left join teacher on course.teach_id=teacher.teacher_id;

----- END -----

posted @ 2017-08-08 23:51  王先生是胖子  阅读(181)  评论(0编辑  收藏  举报