首页 > 解决方案 > 如何使用 PHP 或 MySQL 合并 MySQL 数据库中具有 2 个相同标识符和 2 个唯一标识符的行

问题描述

好的,这是我的第一个问题,我真的不知道如何问,所以我将尝试尽可能具体。我的网站是一个在线游戏,当它将新项目插入数据库时​​用于用户库存

Table name "inventory" 
Column names "inv_id", "inv_itemid", "inv_userid", "inv_qty" 

并且它不会添加到列inv_qty并正确填充,而是为每个项目创建一个新的 inv_id 标识符和行。我想知道是否有办法让我通过 php 创建一个合并函数来合并具有相同 inv_itemid 和 inv_userid 的所有项目,同时添加到 inv_qty 列并填充 inv_id

在我的inventory.php文件中,该inv_id列用于让用户装备该项目或将其用作主要变量。

我已经看到这样做并尝试了很多次,但我无法让它工作。

标签: phpmysql

解决方案


关于:

有没有办法在库存页面顶部编写一个 php 函数供我的用户单击以合并它们

请检查以下 php 函数。

通过使用 param: UserID 调用,它将为每个 (inv_itemid + inv_userid) 组合创建一个包含 inv_qty 总和的新条目,并删除 (inv_itemid + inv_userid) 的先前重复条目,留下新输入的:(inv_itemid + inv_userid + ( inv_qty 的总和))。

重要的是,请在运行函数之前备份数据库表数据。

请检查函数中的注释并根据您的系统在必要时进行更新,例如获取最后插入的 inv_id。

function merger_fnc($user_id) {
    // For Each Combination of: inv_itemid + inv_userid
    // This function will Insert a new row in the inventory with the SUM of inv_qty 
    // And then will remove the previous single rows of: inv_itemid + inv_userid + inv_qty

    // First get the distinct Items of the User(by UserID);
    $inv_itemids = $db->query("SELECT DISTINCT(inv_itemid) FROM inventory WHERE inv_userid=".$user_id);
    // Here $inv_itemids will hold all the distinct ItemIDs for the UserID;

    foreach ($inv_itemids as $inv_item) {
        // We will Insert A new row which will have the sum of 'inv_qty' for the inv_userid & inv_itemid;
        $inv_itemid = $inv_item['inv_itemid'];
        // I am not sure what type of result set your $db->query(...) returns. So I assumed it is associative array. 
        // If the result is an Array of objects, then please use: $inv_itemid = $inv_item->inv_itemid;

        $insert_sql = "INSERT INTO inventory (inv_itemid, inv_userid, inv_qty) VALUES ('".$inv_itemid."', '".$user_id."', (SELECT SUM(inv_qty) FROM FROM inventory WHERE inv_userid=".$user_id."))";
        $inv_itemids = $db->query($insert_sql);

        $inserted_new_inventory_id = $db->insert_id;
        // Please check the appropriate method for it in your $db class here.
        // In mysqli, it is: mysqli_insert_id($db_conn); In PDO it is: $db_conn->lastInsertId();

        // Last we remove the previous data of combination(inv_userid & inv_itemid) but leaving our last inserted row.
        $delete_sql = "DELETE FROM inventory WHERE inv_id!='".$inserted_new_inventory_id."' AND inv_userid='".$user_id."' AND inv_itemid='".$inv_itemid."'";
        $db->query($delete_sql);
    }
}

如果从 $db 获取最后插入的 inv_id 很麻烦(比如 inv_id 未定义为表中的键),您可以尝试另一种方法:

在插入之前执行另一个查询并将先前的 inv_id 保存在一个数组中。插入新条目后,总和为 qty,运行删除查询以删除以前的单个 qty 条目,如下所示:

DELETE FROM inventory WHERE inv_id IN (3, 4, 7,...)
  • 这里 (3, 4, 7,...) 是 (inv_itemid + inv_userid) 组合的先前 inv_id。

推荐阅读