简体   繁体   English

使用PHP将MySQL查询嵌套到UPDATE或INSERT

[英]Nesting MySQL queries to UPDATE or INSERT with PHP

Using MySQL and PHP I'm making an index of the "amounts" table and grouping it by product, type, month, day, and hour. 我使用MySQL和PHP创建“数量”表的索引,并将其按产品,类型,月,日和小时分组。 Then either updating a matching record in the "amounts_merged" table or inserting a new record if it does not already exist. 然后更新“ amounts_merged”表中的匹配记录,或者如果尚不存在则插入新记录。

Here is the solution I came up with. 这是我想出的解决方案。 But I'm not sure this is the best way to go about this. 但是我不确定这是否是实现此目标的最佳方法。 Any suggestions would be great. 任何建议都很好。

$sql = "SELECT product, type, month, day, hour, AVG(amount) AS average_amount FROM amounts GROUP BY product, type, month, day, hour";
$result1 = @mysql_query($sql, $con) or die(mysql_error());

while($row = mysql_fetch_array($result1)) {

    $average_amount = $row[average_amount];
    $product = $row[product];
    $type = $row[type];
    $month = $row[month];
    $day = $row[day];
    $hour = $row[hour];

    $sql = "UPDATE amounts_merged SET average_amount = '$average_amount' WHERE product = '$product' AND type = '$type' AND month = '$month' AND day = '$day' AND hour = '$hour'";
        $result2 = @mysql_query($sql, $con) or die(mysql_error());

        $updated_rows = mysql_affected_rows();

        if ($updated_rows == 0) {

            $sql = "INSERT INTO amounts_merged (product, type, month, day, hour, average_amount)
                        VALUES ('$product', '$type', '$month', '$day', '$hour', '$average_amount')";
            $result3 = @mysql_query($sql, $con) or die(mysql_error());


    }

}

Add a unique key and let MySQL handle it: 添加一个唯一密钥,然后让MySQL处理:

ALTER TABLE amounts_merged  ADD UNIQUE (product,type,month,day,hour)

In PHP: 在PHP中:

 $sql = "INSERT INTO amounts_merged 
    (product,type,month,day,hour,average_amount)
    SELECT product, type, month, day, hour, AVG(amount) AS average_amount
    FROM amounts
    GROUP BY product, type, month, day, hour
    ON DUPLICATE KEY UPDATE average_amount = VALUES(average_amount);"
 mysql_query($sql, $con);

Some loose remarks: 一些宽松的言论:

  • Don't quote variables that are integers or floats (don't know if they are, but I have my suspicions... 不要引用整数或浮点数的变量(不知道它们是否是变量,但我怀疑我...
  • Prepared statements are even more handy for both running more update queries then 1, and in preventing SQL injection. 对于运行多于1个的更新查询以及防止SQL注入而言,准备好的语句更加方便。
  • Having seperate columns for month/date/hour in your original amounts table is probably making live harder then need be, as with just having a timestamp/datetime you can get the data easily from those fiels, and you can still use all date functions easily on the original field. 在原始amounts表中将月份/日期/小时的各个列分开可能会使活得更辛苦,因为只有时间戳/日期时间,您才能轻松地从这些字段中获取数据, 并且仍然可以轻松使用所有日期函数在原始字段上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM