在mysql插入查询中选择Max

时间:2011-04-01 07:18:52

标签: php mysql sql

Max(sequence) + 1(基于我的知识)应该返回数据库中$_GET['business_id']的最高序列+ 1 - 数据库中的现有值是0,1和3 - 所以{{1}应该是4 - 所以代码行必定是错误的。有什么想法吗?

max(sequence)+1

2 个答案:

答案 0 :(得分:4)

删除内部SELECT周围的单引号,而不是常规INSERT,请使用INSERT ... SELECT

$insertQuery = "
    INSERT INTO owner_business_media
        (business_id, sequence, type, filename, title, secret)
    SELECT
        '".intval($_GET['businessid'])."',
        (SELECT MAX(obm.sequence)+1 FROM owner_business_media obm WHERE obm.business_id=".intval($_GET['businessid']).") AS next,
        '$type', 
        '$fullfile', 
        '$filename', 
        '1'
";

此外,永远不要直接嵌入GET变量而不验证或清理它的内容(参见intval($_GET['businessid']))。否则,代码会暴露给SQL injection

答案 1 :(得分:0)

与其他答案几乎相同,但不完全相同:

$insertQuery = "
    INSERT INTO owner_business_media
        (business_id, sequence, type, filename, title, secret)
    SELECT
        '".intval($_GET['businessid'])."',
        MAX(sequence)+1 AS next,
        '$type', 
        '$fullfile', 
        '$filename', 
        '1'
    FROM owner_business_media
    WHERE business_id=".intval($_GET['businessid']);

使用带有sequence的IFNULL(如果表是空的)可能会更安全,如下所示:

        MAX(IFNULL(sequence, 0))+1 AS next