简体   繁体   中英

mysql Creating a temporary table not working…undeclared variable error…whats wrong with my code?

When I run the code below inside phpmyadmin I get an error "Undefined Variable tmpportfolio"

what is the problem?

SQL:

CREATE TEMPORARY TABLE tmpportfolio (p_name VARCHAR(255),portfolio_id INT UNSIGNED NOT NULL);

SELECT p_name, portfolio_id INTO tmpportfolio
    FROM portfolio
    WHERE parent_portfolio_id IS NULL
    AND portfolio_id NOT IN
        (
           SELECT x.parent_portfolio_id
           FROM portfolio x
           WHERE x.parent_portfolio_id IS NOT NULL
        )
    AND account_id = 1

SELECT * FROM tmpportfolio;

SELECT field INTO variable loads the value of the field into a variable. This is why it's complaining about the variable not being defined.

What you need to do is use an INSERT INTO table (colummn) SELECT field statement instead. For instance:

INSERT INTO tmpportfolio (p_name, portfolio_id) 
SELECT p_name, portfolio_id 
FROM portfolio
WHERE parent_portfolio_id IS NULL
AND portfolio_id NOT IN
    (
       SELECT x.parent_portfolio_id
       FROM portfolio x
       WHERE x.parent_portfolio_id IS NOT NULL
    )
AND account_id = 1

You cannot use INTO to insert records into a table in MySql (in SQL Server, you do use INTO that way). In MySql, INTO is used to put a value into a variable.

By doing the SELECT fields INTO tmpportfolio statement, MySql thinks that tmpportfolio is now a variable and it cannot find the variable in the SELECT * .. . The fix is to change the insert-records sql to something like:

INSERT INTO tmpportfolio(p_name,portfolio_id) SELECT ....;

Just join first two SQL statement in one CREATE TABLE ... SELECT statment:

CREATE TABLE tmpportfolio SELECT p_name, portfolio_id FROM portfolio
    WHERE parent_portfolio_id IS NULL
    AND portfolio_id NOT IN
        (
           SELECT x.parent_portfolio_id
           FROM portfolio x
           WHERE x.parent_portfolio_id IS NOT NULL
        )
    AND account_id = 1

SELECT * FROM tmpportfolio;

我无法单独代表mysql,但是通常在创建表后将其插入表中就不会使用selct来创建表(并且因为表已经存在,所以不能使用selct)。

The confusion seems to arise from W3Schools explaining how to do "select into table" without mentioning it's specific to some (non-Mysql) implementations. A page on dev.mysql specifically denies this possibility on Mysql, by saying:

MySQL Server doesn't support the SELECT ... INTO TABLE Sybase SQL extension. Instead, MySQL Server supports the INSERT INTO ... SELECT standard SQL syntax, which is basically the same thing.

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