加入多个表并创建一个表

时间:2013-04-07 05:23:35

标签: mysql sql database doctrine

# tables ans resulting table

我有3张名为Advance,Transport and Medicine的表格。我想加入这三个表,并为emp_id 1创建一个像最后一个表的表。是否可以使用dql(doctrine)或sql在sql级别执行此操作?

1 个答案:

答案 0 :(得分:0)

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

您还可以在此处创建VIEW

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