php 这在单一查询中是否可能?[已关闭]

f4t66c6m  于 2022-12-25  发布在  PHP
关注(0)|答案(1)|浏览(119)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

2天前关闭。
Improve this question
'

protected function getChurnRate($startDate, $endDate) {
        $this->loadModel('Subscription');
        $secondLastSubscriptionsData = $this->Subscription->query("SELECT id,owner FROM `subscriptions` WHERE  planId IN(28) and modified >= '$startDate' and modified <= '$endDate' and id IN(SELECT MAX(id) FROM `subscriptions` WHERE modified >= '$startDate' and modified <= '$endDate' group by owner)");
        $ownerIds = [];
        foreach ($secondLastSubscriptionsData as $secondLastSubscriptionData):
            array_push($ownerIds, $secondLastSubscriptionData['subscriptions']['owner']);
        endforeach;
        $chunkRateData = [];
        if (!empty($ownerIds)):
            $ownerIds = implode(",", $ownerIds);
            $startYear = date('Y', strtotime($startDate));
            $endYear = date('Y', strtotime($endDate));
            $subSql = "SELECT MAX(id) FROM subscriptions WHERE YEAR(modified) >= '$startYear' and YEAR(modified) <= '$endYear' and owner IN($ownerIds) group by owner";
            $sql = "SELECT MAX(id) as maxId FROM `subscriptions` "
                    . "WHERE planId IN(13,29,42) "
                    . "and YEAR(modified) >= '$startYear' "
                    . "and YEAR(modified) <= '$endYear' "
                    . "and id NOT IN($subSql) "
                    . "and owner IN($ownerIds) "
                    . "group by owner";
            $chunkRateData = $this->Subscription->query($sql);
        endif;
        return count($chunkRateData);
    }

'
我试图在一个查询中获取所有数据。这可能吗?
我想在一个单一的转换多个查询,因为上面的代码是非常复杂的,它的执行时间。
帮我解决这个问题。

lndjwyie

lndjwyie1#

如果要合并SELECT MAX(id) FROM subscriptions WHERE YEAR(modified) ...SELECT MAX(id) as maxId FROM订阅WHERE planId IN(13,29,42) ...,可以使用UNIONhttps://www.w3schools.com/sql/sql_union.asp):

(SELECT MAX(id) FROM subscriptions WHERE YEAR(modified) ...) 
UNION 
(SELECT MAX(id) as maxId FROM `subscriptions` WHERE planId IN(13,29,42) ...)

但是,如果您有性能问题,我不确定在一个查询中处理所有内容是否会有所帮助(在某些情况下,这可能会使问题变得更糟)。请考虑使用索引(https://www.w3schools.com/sql/sql_create_index.asp)。modifiedplanIdowner应该被索引,planIdowner应该是外键(https://www.w3schools.com/sql/sql_foreignkey.asp),id应该是主键
EXPLAIN将帮助您排除故障:https://www.exoscale.com/syslog/explaining-mysql-queries/.

相关问题