首页 > 解决方案 > 有没有办法组合 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,没有别的。

标签: phpmysqliquery-optimization

解决方案


您可以为此在 MySQL 中编写存储过程,然后您需要调用该存储过程


推荐阅读