FROM子句在视图中出错

时间:2016-03-17 07:37:46

标签: mysql

创建以下视图时出现错误

    create or replace view viewfee as
    select unique_id,session,course_cat,course,class,rollno, sum(adm_due) as adm_due, sum(tuition_due) as tuition_due, sum(exam_due) as exam_due from 
    (
    select unique_id,session,course_cat,course,class,rollno,null as adm_due, null as tuition_due, null as exam_due from tbstdinfo
    union all
    select unique_id,null,null,null,null,null,(adm_tot - sum(adm_payment)) AS adm_due, null, null from tbfeeadmission group by unique_id
    union all
    select unique_id,null,null,null,null,null,null, (tuition_tot - sum(tuition_payment)) AS tuition_due, null from tbfeetuition group by unique_id
    union all
    select unique_id,null,null,null,null,null,null, null, (exam_tot - sum(exam_payment)) AS exam_due from tbfeeexam group by unique_id
    )x
    group by unique_id

但如果我执行没有视图的查询,它可以正常工作

select unique_id,session,course_cat,course,class,rollno, sum(adm_due) as adm_due, sum(tuition_due) as tuition_due, sum(exam_due) as exam_due from 
(
select unique_id,session,course_cat,course,class,rollno,null as adm_due, null as tuition_due, null as exam_due from tbstdinfo
union all
select unique_id,null,null,null,null,null,(adm_tot - sum(adm_payment)) AS adm_due, null, null from tbfeeadmission group by unique_id
union all
select unique_id,null,null,null,null,null,null, (tuition_tot - sum(tuition_payment)) AS tuition_due, null from tbfeetuition group by unique_id
union all
select unique_id,null,null,null,null,null,null, null, (exam_tot - sum(exam_payment)) AS exam_due from tbfeeexam group by unique_id
)x
group by unique_id

实际上我需要组合四个表来在一个表中获取所有需要的记录。请帮忙

2 个答案:

答案 0 :(得分:1)

  

在MySQL 5.7.7之前,SELECT语句不能包含子查询   FROM子句。

参考:

http://dev.mysql.com/doc/refman/5.7/en/create-view.html

答案 1 :(得分:1)

您不能在视图定义中使用子选择,但是您可以执行以下操作:

create or replace view intermediate_view as
select unique_id,session,course_cat,course,class,rollno,null as adm_due, null as tuition_due, null as exam_due from tbstdinfo
union all
select unique_id,null,null,null,null,null,(adm_tot - sum(adm_payment)) AS adm_due, null, null from tbfeeadmission group by unique_id
union all
select unique_id,null,null,null,null,null,null, (tuition_tot - sum(tuition_payment)) AS tuition_due, null from tbfeetuition group by unique_id
union all
select unique_id,null,null,null,null,null,null, null, (exam_tot - sum(exam_payment)) AS exam_due from tbfeeexam group by unique_id

然后

create or replace view viewfee as
select unique_id,session,course_cat,course,class,rollno, sum(adm_due) as adm_due, sum(tuition_due) as tuition_due, sum(exam_due) as exam_due from intermediate_view
group by unique_id

作为解决方法