php - 如何使用 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
列用于让用户装备该项目或将其用作主要变量。
我已经看到这样做并尝试了很多次,但我无法让它工作。
解决方案
关于:
有没有办法在库存页面顶部编写一个 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。
推荐阅读
- r - 使用 misc3d 绘制平滑的隐式曲面
- .net - 图标是像素化的图片框
- mysql - 按我的 sql 中的一个字段分组并将另一个字段值连接为一个字符串
- php - 为什么我不能使用 PHP 访问类中的函数
- c# - 路由中的枚举序列化
- token - 如何将 ERC20 代币持有者的钱包地址保密?
- scala - 从 RDD 中获取 HashMap
- javascript - 使用 automator 打开 Photoshop 并运行外部 javascript
- d3.js - 主 D3 模块命名空间是否不会随着最前沿的子模块添加而更新?
- swift - TextField 不会从 RealmSwift 加载