php - 有没有办法组合 mysqli 查询或给它们一个优化序列?
问题描述
我想知道是否可以优化我的查询以避免发送十个请求,检查三个主表和两个复合表是否具有所需的元素,如果没有则插入它们。
(“复合表”是我所说的包含两个主键的表,这两个主键都是对另一个表中主键的引用,因为我不知道正确的术语)
所以我试图看看我是否可以在一个查询中从三个主表中获取所有需要的 id,但我无法让它工作。
这是我尝试过的一些事情。
select t1.a AS EID, t2.a AS CID, t3.a AS IID from (select ID as a from Events where event = "test3") as t1, (select ID as a from Coordinates where Coordinates = "10.22,14.15") as t2, (select ID as a from Intervals where Interval = "From 12:15 To 18:30") as t3;
SELECT ID AS eid FROM Events WHERE event = "test3" UNION ALL SELECT ID AS cid FROM Coordinates WHERE Coordinates = "10.22,14.15" UNION ALL SELECT ID AS iid FROM Intervals WHERE Interval = "From 12:15 To 18:30"
这就是我目前正在做的
if(!empty($this->event) && $this->event!== false){
$sql = "SELECT ID FROM Events WHERE event = ?";
$values = array($this->event);
$db->setQuery($sql, $values);
$db->singleFetch();
if($db->getResults() == 1){
$eid = $db->getFetch()[0]['ID'];
}
else{
$sql = "INSERT INTO Events (event, Description) VALUES (?, ?)";
$values = array($this->event, $this->description);
$db->setQuery($sql, $values);
$db->singleQuery();
$eid = $db->getLast();
}
}
//I am doing this for all three main tables,
//to get the ids needed for me to be able to do this.
if(isset($eid) && isset($cid)){
$sql = "SELECT count(*) FROM EC WHERE EID = ? AND CID = ?";
$values = array($eid, $cid);
$db->setQuery($sql, $values);
$db->singleFetch();
if($db->getFetch()[0]['count(*)'] == 0){
$sql = "INSERT INTO EC (EID, CID) VALUES (?, ?)";
$values = array($eid, $cid);
$db->setQuery($sql, $values);
$db->singleQuery();
}
}
//Which i then do for both composite tables
要么我用所有可能的组合得到我的 fetch 数组,要么我什至没有得到我的 fetch 数组,其他时候我得到了它,但有两个相同的事件 id,没有别的。
解决方案
您可以为此在 MySQL 中编写存储过程,然后您需要调用该存储过程
推荐阅读
- python - 使用 HTMLTestRunner 模块时发生错误
- reactjs - create-react-app bash: /usr/local/bin/create-react-app: 没有这样的文件或目录
- python - QTableWidget Joint Cells 问题:水平连接一系列单元格后,然后我一般连接单元格,所选单元格发疯
- reactjs - 如何推入与我传递给 api 的主体相对应的数组?
- scala - 我想运行一个 scala 文件并期望输出
- r - 矩阵上的下标数不正确。同时将数据帧中的值分配给矩阵
- swift - 禁用 ObservableObject 中 @Published 变量的发送事件
- java - 每次 Oracle 发布更新时,我是否需要更新 JAVA JDK?
- c# - Winforms 标签页上的关闭按钮
- azure-logic-apps - 如何在逻辑应用程序中创建和格式化 HTML 表格