我在 PHP 和 Mysql 项目中有一个问题。
简单地说,我有两个表项目和项目功能,
每个项目都有特定的功能。
CREATE TABLE projects (
ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(255) NOT NULL
);
CREATE TABLE projects_features (
projectId INT NOT NULL,
name varchar(255) NOT NULL,
value varchar(255) NOT NULL,
weight INT NOT NULL
);
INSERT INTO projects VALUES (NULL,'project1');
INSERT INTO projects VALUES (NULL,'project2');
INSERT INTO projects_features VALUES (1,'Feature1','Feature1 Value',1);
INSERT INTO projects_features VALUES (2,'Feature2','Feature2 Value',2);
INSERT INTO projects_features VALUES (1,'Feature3','Feature3 Value',3);
INSERT INTO projects_features VALUES (2,'Feature4','Feature4 Value',4);
INSERT INTO projects_features VALUES (1,'Feature5','Feature5 Value',5);
我通过以下方式获取项目功能:
SELECT * FROM projects_features WHERE projectId = 1 ORDER BY weight ASC;
因此较大的权重将向下,较小的权重将向上。
现在, 在“我的 View ”中,我有上移和下移按钮,因此我可以对项目功能重新排序。
我可以先选择当前的元素重量,然后选择上面的元素重量,
然后输入两个更新查询来交换两行之间的权重,
但这不是专业的方式,我不喜欢使用四个查询。
我需要在一个查询中完成此操作,而不是四个查询。
有人可以帮忙吗?
最佳答案
假设我已经理解了这个问题,这就是我解决这个问题的方法。
首先,我将 featureId
列添加到 projects_features
中,并将 (projectId, featureId)
设为复合主键。对于我的解决方案来说,这实际上并不是必需的;它只会让剩下的事情变得更加容易。对于下一部分,您需要能够引用 projects_features
中的各个记录。
接下来,我将使用 Move
按钮填充 PHP 中的数组,例如
$update_list = array();
$update_list[i] = array(':project_id' => $proj_id,
':feature_id' => $feat_id,
':new_weight' => $weight);
最后,我将通过封装 UPDATE
语句的 PHP 函数进行更新,如下所示:
function updateWeights($update_array, $dbh)
{
$sql = 'UPDATE project_features
SET weight = :new_weight
WHERE projectId = :project_id
AND featureId = :feature_id'
$stmt = $dbh->prepare($sql);
foreach ($update_array as $update_item)
{
$stmt->execute($update_item);
}
}
注意我在这里使用 PDO;也可以使用 mysqli 来完成,尽管 mysqli 不支持命名绑定(bind)参数,因此语法会略有不同,例如
function updateWeights($update_array, $dbh)
{
$sql = 'UPDATE project_features
SET weight = ?
WHERE projectId = ?
AND featureId = ?'
$stmt = $dbh->prepare($sql);
foreach ($update_array as $update_item)
{
$stmt->bind_param('i', $update_item[':new_weight']);
$stmt->bind_param('i', $update_item[':project_id']);
$stmt->bind_param('i', $update_item[':feature_id']);
$stmt->execute();
}
}
另请注意,我尚未实际运行此代码,因此不表示它没有语法或其他错误。
希望对您有所帮助。
关于php - Mysql中的排序机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926018/