优化这段sql:SELECT `msisdn`, `relationship_account` AS relationshipAccount, '' AS relationshipName, IFNULL(SUM( `dual_time` ), 0) AS totalTime, IFNULL(COUNT(1), 0) AS totalCall, IFNULL(SUM(`local_action` = (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '07')), 0) AS active, IFNULL(SUM(`local_action` = (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '08')), 0) AS passive, IFNULL(SUM(`call_status` = (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '09')), 0) AS success, IFNULL(SUM(`call_status` = (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '10')), 0) AS fail, FROM_UNIXTIME(MIN(UNIX_TIMESTAMP(`start_time`))) AS onceCallTime, FROM_UNIXTIME(MAX(UNIX_TIMESTAMP(`start_time`))) AS endCallTime FROM `dwd_t_call_record` WHERE `person_no` = '653129200105072624' GROUP BY `relationship_account` ORDER BY `start_time` ASC
时间: 2024-03-13 14:44:47 浏览: 51
可以优化的地方有:
1. 子查询可以改为使用 JOIN,例如:
```
SELECT status_description
FROM dwd_t_code_value
WHERE storage_status = '07'
```
改为:
```
SELECT t2.status_description
FROM (
SELECT status_description, storage_status
FROM dwd_t_code_value
) t2
WHERE t2.storage_status = '07'
```
2. 使用 EXISTS 或者 IN 替换掉子查询,例如:
```
IFNULL(SUM(`local_action` = (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '07')), 0) AS active
```
改为:
```
IFNULL(SUM(`local_action` IN (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '07')), 0) AS active
```
或者:
```
IFNULL(SUM(EXISTS (SELECT 1 FROM dwd_t_code_value WHERE storage_status = '07' AND status_description = `local_action`)), 0) AS active
```
3. 可以考虑将 FROM_UNIXTIME 和 UNIX_TIMESTAMP 改为 DATE_FORMAT 和 STR_TO_DATE,以避免频繁的数据类型转换。
综上所述,优化后的 SQL 可能类似于以下内容:
```
SELECT
`msisdn`,
`relationship_account` AS relationshipAccount,
'' AS relationshipName,
IFNULL(SUM(`dual_time`), 0) AS totalTime,
IFNULL(COUNT(1), 0) AS totalCall,
IFNULL(SUM(`local_action` IN (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '07')), 0) AS active,
IFNULL(SUM(`local_action` IN (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '08')), 0) AS passive,
IFNULL(SUM(`call_status` IN (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '09')), 0) AS success,
IFNULL(SUM(`call_status` IN (SELECT status_description FROM dwd_t_code_value WHERE storage_status = '10')), 0) AS fail,
DATE_FORMAT(MIN(STR_TO_DATE(`start_time`, '%Y-%m-%d %H:%i:%s')), '%Y-%m-%d %H:%i:%s') AS onceCallTime,
DATE_FORMAT(MAX(STR_TO_DATE(`start_time`, '%Y-%m-%d %H:%i:%s')), '%Y-%m-%d %H:%i:%s') AS endCallTime
FROM
`dwd_t_call_record`
WHERE
`person_no` = '653129200105072624'
GROUP BY
`relationship_account`
ORDER BY
`start_time` ASC
```
阅读全文