我的数据库中有数百万个条目。
因为我正在使用3 !!内连接并放置大范围的日期,这个查询需要很长时间,比如几分钟。
有没有办法改进此查询并仍能获得相同的数据?
这是我的疑问:
SELECT
subscriptions.service_id,
service_send_type.usage,
service_send_type.price, SUM(IF(msg_t.status LIKE 'Success%', 1, 0)) AS s,
COUNT(1) AS t
FROM (`subscriptions`)
INNER JOIN
`msg_t` ON `subscriptions`.`phone` = `msg_t`.`phone` AND subscriptions.id = msg_t.sub_id
INNER JOIN
`msg` ON `msg`.`id` = `msg_t`.`msg_id`
INNER JOIN `service_send_type` ON `msg`.`service_id` = `service_send_type`.`service_id`
AND msg.sushi_service_id = service_send_type.sushi_service_id
AND msg.send_type = service_send_type.name
AND msg.service_id = subscriptions.service_id
WHERE
`subscriptions`.`service_id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
AND
`subscriptions`.`added` >= '2013-01-28 00:00:00'
AND
`subscriptions`.`added` <= '2013-01-28 23:59:59'
AND
`msg_t`.`send_time` >= '2013-01-28 00:00:00'
AND
`msg_t`.`send_time` <= '2013-01-28 23:59:59'
GROUP BY
`subscriptions`.`service_id`,
`service_send_type`.`usage`,
`service_send_type`.`price`
答案 0 :(得分:2)
您可以尝试optimize your query by analyzing the Explain plan,包括index optimizing,如果您的桌子上仍然没有idnexes,这可能会非常有用。关于语句优化,请查看here。
希望这有助于你进一步
答案 1 :(得分:2)
您是否始终需要IN
查询?在您的查询中,IN子句可以替换为subscriptions.service_id < 17
,这将产生巨大的差异。当您有离散值列表时,IN查询是合适的。
另请查看表上的索引。您应该在where
条件和group by
子句中的列上设置索引。