简体   繁体   中英

Join multiple tables and create a single table

#个表和结果表

I having 3 tables called Advance, Transport and Medicine. I want to join these three tables and come up with a table like last one for emp_id 1. Is it possible to do this in sql level using dql (doctrine) or sql?

CREATE TABLE NewTable
SELECT  Date, 
        Emp_ID,
        Amount As Advance, 
        NULL AS Transport,
        NULL AS Medicine
FROM    Advance
WHERE   Emp_ID = 1           -- remove this WHERE clause to include all emp_ID
UNION   ALL
SELECT  Date, 
        Emp_ID,
        NULL As Advance, 
        Amount AS Transport,
        NULL AS Medicine
FROM    Transport
WHERE   Emp_ID = 1           -- remove this WHERE clause to include all emp_ID
UNION   ALL
SELECT  Date, 
        Emp_ID,
        NULL As Advance, 
        NULL AS Transport,
        Amount AS Medicine
FROM    Medicine
WHERE   Emp_ID = 1           -- remove this WHERE clause to include all emp_ID

You can also create a VIEW on this,

CREATE VIEW EmployeeView
AS
SELECT  Date, 
        Emp_ID,
        Amount As Advance, 
        NULL AS Transport,
        NULL AS Medicine
FROM    Advance
WHERE   Emp_ID = 1           -- remove this WHERE clause to include all emp_ID
UNION   ALL
SELECT  Date, 
        Emp_ID,
        NULL As Advance, 
        Amount AS Transport,
        NULL AS Medicine
FROM    Transport
WHERE   Emp_ID = 1           -- remove this WHERE clause to include all emp_ID
UNION   ALL
SELECT  Date, 
        Emp_ID,
        NULL As Advance, 
        NULL AS Transport,
        Amount AS Medicine
FROM    Medicine
WHERE   Emp_ID = 1           -- remove this WHERE clause to include all emp_ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM