MySQL-----连表

SQL连接查询详解

连表:

 

  **拿到两张表的信息**

  select * from userinfo,department

    弊端是数据会乱,出现重复,不建议这样。

  **使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

 

转载于:https://www.cnblogs.com/george92/p/7309734.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值