在mySQL中,如何在一个查询中获取和设置值?

时间:2014-12-03 16:52:25

标签: php mysql

我正在尝试获取表中最高的行顺序号,将其设置为变量,增加它,然后将新数据作为新记录插入。 该脚本使用PHP,$ SQL适用于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;

这是错误:您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以便在#2; SET lineOrder =(SELECT IFNULL(Line Order,1)FROM router'第2行附近使用正确的语法/ p>

1 个答案:

答案 0 :(得分:1)

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