已关闭。此问题需要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);
}
'
我试图在一个查询中获取所有数据。这可能吗?
我想在一个单一的转换多个查询,因为上面的代码是非常复杂的,它的执行时间。
帮我解决这个问题。
1条答案
按热度按时间lndjwyie1#
如果要合并
SELECT MAX(id) FROM subscriptions WHERE YEAR(modified) ...
和SELECT MAX(id) as maxId FROM
订阅WHERE planId IN(13,29,42) ...
,可以使用UNION
(https://www.w3schools.com/sql/sql_union.asp):但是,如果您有性能问题,我不确定在一个查询中处理所有内容是否会有所帮助(在某些情况下,这可能会使问题变得更糟)。请考虑使用索引(https://www.w3schools.com/sql/sql_create_index.asp)。
modified
、planId
、owner
应该被索引,planId
和owner
应该是外键(https://www.w3schools.com/sql/sql_foreignkey.asp),id
应该是主键EXPLAIN
将帮助您排除故障:https://www.exoscale.com/syslog/explaining-mysql-queries/.