我的数据库结构遇到了一些性能问题“或者更好地说我的查询”
我有一张下表:
http://sqlfiddle.com/#!9/348cb
然后在尝试获取某些数据的查询之后,然后尝试检查是否有其他记录符合我的条件,这一切都在以下查询中。
它正在按预期工作,我问这个问题的唯一原因是,如果有办法,我可以提高其性能或使用另一种方式来获得结果。
如您所见,有两个( SELECT )
试图检查是否有任何其他记录包含当前查询数据。
SELECT (
SELECT COUNT(*) FROM log AS LIKES
WHERE L.target_account=LIKES.target_account
AND LIKES.type='like'
) as liked,
(
SELECT COUNT(*) FROM log AS COMMENTS
WHERE L.target_account=COMMENTS.target_account
AND COMMENTS.type='follow_back'
) as follow_back,
(
SELECT COUNT(*) FROM log AS FOLLOW_BACK
WHERE L.target_account=FOLLOW_BACK.target_account
AND COMMENTS.type='follow_back'
) as follow_back,
L.*
FROM `log` as L
WHERE `L`.`information` = '".$target_name."'
AND `L`.`account_id` = '".$id."'
AND `L`.`date_ts` BETWEEN CURDATE() - INTERVAL ".$limit." DAY AND CURDATE()
此查询需要花费太多时间来获取数据。 提前谢谢。
答案 0 :(得分:0)
SELECT SUM(LIKES) LIKES,SUM(FOLLOW_BACK) FOLLOW_BACK,SUM(COMMENTS) FROM
(
SELECT
CASE WHEN L.type='like' THEN 1 ELSE 0 END LIKES,
CASE WHEN L.type='follow_back' THEN 1 ELSE 0 END FOLLOW_BACK,
CASE WHEN L.type='comments' THEN 1 ELSE 0 END COMMENTS
FROM `log` as L
WHERE `L`.`information` = '".$target_name."'
AND `L`.`account_id` = '".$id."'
AND `L`.`date_ts` BETWEEN CURDATE() - INTERVAL ".$limit." DAY AND CURDATE()
)Z
尝试以上查询。
希望这会对你有所帮助。
答案 1 :(得分:0)
您可以重写查询,具体取决于目标帐户和帐户ID之间的关系。
与此同时,您需要索引。您想要的两个是instagram_log(target_account, type)
和instagram_log(account_id, information, date_ts)
:
create index idx_instagram_log_1 on instagram_log(target_account, type);
create index idx_instagram_log_2 on instagram_log(account_id, information, date_ts);