简体   繁体   中英

In mySQL, how do I get and set a value in one query?

I am trying to get the highest Line Order number in the table, set it to a variable, increment it, then insert it with new data as a new record. The script is in PHP and $SQL is for mySQL

$SQL="  
      BEGIN
        DECLARE lineOrder INT DEFAULT 1;
        SET lineOrder = (
           SELECT IFNULL(`Line Order`,1)
           FROM `router`
           ORDER BY `Line Order` DESC
           lIMIT 1);
        lineOrder = lineOrder + 1;
        INSERT INTO `router`(`Line Order`, `Estimated Time`,
                               `Estimated Time Unit`, `Work Center`,
                               `Work Description`)
        VALUES (lineOrder,?,?,?,?);
      END;
    ";
$stmt = $GLOBALS['mySQLConnection']->prepare($SQL);
echo $GLOBALS['mySQLConnection']->error;

This is the error: 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 'SET lineOrder = (SELECT IFNULL( Line Order ,1) FROM router ' at line 2

INSERT INTO `router` (`Line Order`,
     `Estimated Time`, `Estimated Time Unit`, `Work Center`, `Work Description`)
SELECT 1 + IFNULL(MAX(`Line Order`), 0),
     ?, ?, ?, ?
FROM `router`

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