今天,我收到的电子邮件从我的托管帐户说,我需要调整我的查询:与子查询的MySQL优化查询
SELECT
`id`, `nick`, `msg`, `uid`, `show_pic`,
`time`,`ip`,`time_updated`,
(SELECT COUNT(c.msg_id)
FROM `the_ans` c
where c.msg_id = d.id) AS counter,
(SELECT c.msg
FROM `the_ans` c
WHERE c.msg_id=d.id
ORDER BY `time` DESC LIMIT 1) as lastmsg
FROM
`the_data` d
ORDER BY `time_updated` DESC LIMIT 26340 ,15
说明:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY d ALL 34309 Using filesort
3 DEPENDENT SUBQUERY c ALL 43659 Using where; Using filesort
2 DEPENDENT SUBQUERY c ALL 43659 Using where
这个查询检查65,396,669,012,829行,这在共享主机中是不可接受的。
TBH,我不明白他们的解释.. 什么查询实际上并是时间去15个职位顺序更新, 每篇文章我抢的最新评论, 计数每个帖子所有评论。
posts table - 'the_data'
comments table = 'the_ans'
我不是一个MySQL的大师,我不知道如何改进这个查询 任何帮助将不胜感激
THX
查询
SELECT
`id` , `nick` , `msg` , `uid` , `show_pic` , `time` , `ip` , `time_updated` , (
SELECT COUNT(c.msg_id)
FROM `the_ans` c
WHERE c.msg_id = d.id
) AS counter, (
SELECT c.msg
FROM `the_ans` c
WHERE c.msg_id = d.id
ORDER BY `time` DESC
LIMIT 1
) AS lastmsg
FROM `the_data` d
ORDER BY `time_updated` DESC
LIMIT 26340 , 15
这是结果结构
id| nick | msg | uid | show_pick | time | ip |time_updated|counter|lastmsg
| | | | | | | | |
7 | jqman | hello| 10074 | 0 |2013-21-01 | 12 |2013-21-01 | 55 |blah bl
您确定'LIMIT 26340,15'部分? – inhan
基本的问题是需要执行查询来获得15行。要执行你的主查询,每个子查询都需要为每一行处理执行。你可以发布每个表的show create table的结果吗?你是否在每个表中创建了“id”的索引? – Jaydee
通常,不相关的子查询将比关联的子查询执行得更好。通用语法如下:SELECT x。* FROM my_table x JOIN(SELECT id,MAX(time)max_time FROM my_table GROUP BY id)y ON y.id = x.id AND y.max_time = x.time;这将在每个线程中为您提供最新的消息。然后,你只需加入其他信息(或反之亦然) – Strawberry