有没有办法组合 mysqli 查询或给它们一个优化序列?

Posted

技术标签:

【中文标题】有没有办法组合 mysqli 查询或给它们一个优化序列?【英文标题】:Is there a way to combine mysqli queries or give them a sequence for optimization? 【发布时间】:2019-02-08 11:30:42 【问题描述】:

我想知道是否可以优化我的查询以避免发送十个请求,检查三个主表和两个复合表是否具有所需的元素,如果没有,则插入它们。

(“复合表”是我所说的包含两个主键的表,这两个主键都是对另一个表中主键的引用,因为我不知道正确的术语)

所以我试图查看是否可以在一个查询中从三个主表中获取所有需要的 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,没有别的。

【问题讨论】:

***.com/questions/1775168/… 【参考方案1】:

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

【讨论】:

这听起来很有趣,我肯定会研究它,但据我所知,我更喜欢这样的事情。 ***.com/a/1775272/9912983 减少通话次数。

以上是关于有没有办法组合 mysqli 查询或给它们一个优化序列?的主要内容,如果未能解决你的问题,请参考以下文章

有没有办法优化这个查询

我正在制作一个 SQLite 数据库,但我有许多类似的表 - 有没有办法将它们组合起来?

陷入困境的疑问

有没有办法将数组绑定到mysqli准备[重复]

有没有办法通过使用 FirestoreRecyclerAdapter 组合查询游标来对查询进行分页?

PHP - 在 mysqli 查询中使用数组