MySQL三张表联合创建一个新视图


联合表就需要先提到几个关键字


先说说 union all 和 union 区别:

1.UNION 操作符用于合并两个或多个 SELECT 语句的结果集。

请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。

SQL UNION 语法

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

注释:默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。


2.

UNION ALL

UNION ALL 命令和 UNION 命令几乎是等效的,不过 UNION ALL 命令会列出所有的值。

SQL Statement 1
UNION ALL
SQL Statement 2

使用 UNION ALL 命令

实例:

列出在中国和美国的所有的雇员:

SELECT E_Name FROM Employees_China
UNION ALL
SELECT E_Name FROM Employees_USA

现在进入正题:

联合三张表创建新视图:

create or replace view v_ms_reconductplanunvaliable as


     
        select r.fuseplanid,r.fuseplandetid,r.fmaterialid,r.fbatch,
            sum(IFNULL(r.frecnum,0)*IFNULL(r.ftranRelation,1)) as unvaliableNum
            from t_ms_receiveconductdet r ,t_ms_receiveconduct t where t.fpid=r.freceiveconductid and t.fuse='计划领用' and t.fstatus=0
            group by r.fuseplanid,r.fuseplandetid,r.fmaterialid,r.fbinid,r.fbatch
        
        union all 
         
                select r.fuseplanid,r.fuseplandetid,r.fmaterialid,r.fbatch,
                sum(IFNULL(r.fapprovenum,0)*IFNULL(r.ftranRelation,1)) as unvaliableNum
                from t_ms_receiveconductdet r ,t_ms_receiveconduct t where t.fpid=r.freceiveconductid and t.fuse='计划领用' and (t.fstatus=2 or t.fstatus=3 or t.fstatus=4)
                 group by r.fuseplanid,r.fuseplandetid,r.fmaterialid,r.fbinid,r.fbatch
        
        union all 
        
              select r.fuseplanid,r.fuseplandetid,r.fmaterialid,r.fbatch,
              sum(IFNULL(r.foutnum,0)*IFNULL(r.ftranRelation,1)) as unvaliableNum
              from t_ms_receiveconductdet r ,t_ms_receiveconduct t where t.fpid=r.freceiveconductid and t.fuse='计划领用' and t.fstatus=7
               group by r.fuseplanid,r.fuseplandetid,r.fmaterialid,r.fbinid,r.fbatch;


其基本sql 语法就是:

  1. create view vall as
  2. select a.photo,a.type,a.update_time from action a union all
  3. select p.id,2,p.create_time from photo p union all
  4. select c.photo,3,c.update_time from comment c;  

       
          

你可能感兴趣的:(数据库)