如何在SQL中使用临时表

时间:2012-12-08 13:32:38

标签: mysql sql

我曾尝试使用临时表来简化查询,但收到错误消息。 这是我的疑问:

SELECT E.ID, E.name
INTO #TmpEmplyee
FROM Employee E, Outsourcing O, Student S
WHERE E.ID NOT IN (SELECT ID FROM Student UNION SELECT ID FROM Outsourcing)

SELECT R.name, I.startDate, T.name
FROM Role R, Inn I, #TmpEmplyee T
WHERE I.name = R.name AND I.ID = T.id

错误是:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Employee E, Outsourcing O, Student S WHERE E.ID NOT IN (SELECT ID FROM Stud' at line 3

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

在mysql中,您需要在查询之前创建临时表。你也不需要在FROM中外包O,学生S,因为你没有从中选择:

INSERT INTO #TmpEmplyee
SELECT E.ID, E.name
FROM Employee E
WHERE E.ID NOT IN (SELECT ID FROM Student UNION SELECT ID FROM Outsourcing)

答案 1 :(得分:1)

尝试一下,

SELECT R.name, I.startDate, T.name
FROM    Role R 
        INNER JOIN Inn I
            ON I.name = R.name
        INNER JOIN
        (
            SELECT E.ID, E.name
            -- remember that the join below produces CROSS JOIN
            FROM Employee E, Outsourcing O, Student S
            WHERE E.ID NOT IN ( SELECT ID FROM Student 
                                UNION 
                                SELECT ID FROM Outsourcing)
        ) T ON I.ID = T.id

答案 2 :(得分:0)

要从选择中创建临时表,您应该使用此语法

CREATE TEMPORARY TABLE mytemptable 
SELECT Field1, Field2 
FROM mytable;