mysql笔记补充

两张表联合为一张表 union-联合

select student_id,student_name

from t_student

UNION

select c_id,c_name

from t_class

笛卡尔乘积

select student_id,student_name,student_sex,c_name

from t_student,t_class

笛卡尔乘积过滤

select student_id,student_name,student_sex,c_name

from t_student,t_class

where t_student.student_c_id=t_class.c_id

内连接的 第一种写法

这种写法的优点是简单明了 直接笛卡尔乘积,然后过滤外键=主键

缺点就是 主外键的关联过滤与其他条件的过滤全部都写在where条件中

select student_id,student_name,student_sex,c_name

from t_student,t_class

where t_student.student_c_id=t_class.c_id and student_name like '%三%'

第二种写法 使用 表1 inner join 表2 on 表1.xxxid=表2.xxxid(主外键的对应)

select student_id,student_name,student_sex,c_name

from t_student

INNER JOIN t_class on t_student.student_c_id=t_class.c_id

第二种写法 多张表,建议大家先写中间表(连接较多的外键表)

SELECT employee_name,employee_sex,post_name,branch_name

from employee as emp

INNER JOIN branch as b on emp.branch_id=b.id

INNER JOIN post as p on emp.post_id=p.id

外链接 分为 左外连接 左边的表示主要要查询的表 和右外连接 右边的表是主要要查询的表

外链接的意思是: 作为主要要查询的表,无论另外一张表是否有数据和他关联

主要要查询的表里面的数据必须都要查询出来

posted @ 2019-12-27 17:06  现在不晓得  阅读(112)  评论(0)    收藏  举报