MySql更新无法识别临时表

时间:2017-04-20 13:09:34

标签: mysql sql subquery temp-tables

我有以下查询脚本导致错误:

SET @row_number = 0;

Drop Table If Exists testtable2;

Create Temporary Table testtable2
SELECT 
    *
FROM
    (SELECT 
        row_names, (@row_number:=@row_number + 1) AS num, date_add(date_time, INTERVAL 1 MINUTE) AS date_time, meter, kw
    FROM
        testtable
    WHERE
        DAY(date_time) = 1
            AND HOUR(date_time) = 2) AS testtable2
WHERE
    MOD(testtable2.num, 2) = 0;

UPDATE testtable 
SET 
    testtable.date_time = testtable2.date_time
WHERE
    testtable.row_names = testtable2.row_names;

错误说Error Code: 1054. Unknown column 'testtable2.row_names' in 'where clause'

我创建了一个包含date_time列的临时表,但我的更新查询无法识别该列是否存在。我可以运行SELECT * FROM testtable2;并返回显示该列确实是使用正确的标题生成的。为什么我的更新无法识别此列?

2 个答案:

答案 0 :(得分:1)

你实际上是想使用CREATE TABLE ... AS构造,但在你的情况下它是错误形成的。它应该如下所示。

Create Temporary Table testtable2 AS
SELECT 
    *
FROM
    (SELECT 
        row_names, (@row_number:=@row_number + 1) AS num,
      date_add(date_time, INTERVAL 1 MINUTE) AS date_time, 
      meter, 
      kw
    FROM
        testtable
    WHERE
        DAY(date_time) = 1
            AND HOUR(date_time) = 2) AS XXX <-- Here
WHERE
    MOD(testtable2.num, 2) = 0;

您的案例中的问题是,您的临时表和内联视图别名是相同的。用不同的名字命名请参阅编辑过的查询。

您可以使用内部查询直接JOIN,并可以像

一样执行UPDATE
UPDATE testtable 
JOIN (
SELECT 
    *
FROM
    (SELECT 
        row_names, (@row_number:=@row_number + 1) AS num, date_add(date_time, INTERVAL 1 MINUTE) AS date_time, meter, kw
    FROM
        testtable
    WHERE
        DAY(date_time) = 1
            AND HOUR(date_time) = 2) AS testtable2
WHERE
    MOD(testtable2.num, 2) = 0 ) xx ON testtable.row_names = xx.row_names
SET 
    testtable.date_time = xx.date_time;

答案 1 :(得分:1)

这是您的UPDATE testtable SET testtable.date_time = testtable2.date_time WHERE testtable.row_names = testtable2.row_names; 声明:

testtable

什么是testtable2?你还没有定义。您创建了testtable。如果您确实有join,那么您可能需要UPDATE testtable tt JOIN testtable2 tt2 ON tt.row_names = tt2.row_names SET tt.date_time = tt2.date_time;

progressBar.set_fraction(0);

1 simulation
progressBar.set_fraction(progressBar.get_fraction()+1/5)


2 simulation
progressBar.set_fraction(progressBar.get_fraction()+1/5)


3 simulation
progressBar.set_fraction(progressBar.get_fraction()+1/5)


4 simulation
progressBar.set_fraction(progressBar.get_fraction()+1/5)


5 simulation
progressBar.set_fraction(progressBar.get_fraction()+1/5)