CREATE VIEW student_grade_view
AS select stu.*,gra.* from student as stu INNER join grade as gra on stu.grade_id=gra.id
注意:‘as’指的是另起一个别名
上述语句展示信息为学生表所有字段和年级表的所有字段(因为都是*)
那么就存在一个问题:两张表共同存在的字段就会重名
怎么解决呢?
第二张表的字段用‘表名.字段名’的方式进行展示,这样就可以给字段名其别名了
那么修改后的语句就是:
CREATE VIEW student_grade_view
AS select stu.*,gra.id as gra_id,gra.grade_name as gra_gradeName from student as stu INNER join grade as gra on stu.grade_id=gra.id
4 最佳实践
4.1 通过表student带出表grade
CREATE VIEW student_grade_view
select stu.*,gra.* from student stu left join grade gra on stu.grade_id=gra.id
CREATE VIEW student_grade_view
AS select stu.*,gra.id as gra_id,gra.grade_name as gra_gradeName from student as stu left join grade as gra on stu.grade_id=gra.id
4.2 通过表middle带表student和表grade
CREATE VIEW student_grade_view
As select stu.*,gra.* from middle mid left join grade gra on mid.grade_id=gra.id left join student stu on mid.student_id=stu.id
4.3 通过表middle(字段重复写别名)带表student和表grade
CREATE VIEW student_grade_view
As select stu.*,mid.id as mid_id,mid.grade_id as mid_grade_id from middle as mid left join student as stu on mid.student_id=stu.id
4.4 通过表middle带表student再带出表grade
CREATE VIEW student_grade_view
As select stu_mid.*,gra.grade_name,gra.id as gra_id from (SELECT stu.*,mid.id as mid_id,mid.grade_id as mid_grade_id from middle as mid left join student as stu on mid.student_id=stu.id) as stu_mid
left join grade gra on stu_mid.grade_id=gra.id
4.5 通过表student的两个字段带出两次表grade
CREATE VIEW student_grade_view
select stu.*,gra.grade_name as gra_gradeName,gra2.grade_name as gra2_gradeName
from student stu
left join grade gra on stu.grade_id=gra.id
left join grade gra2 on stu.grade2_id=gra2.id