mysql - What is the difference between subquery and a joined subquery? -
what difference between these 2 mysql queries
select t.id, (select count(c.id) comment c c.topic_id = t.id) comments_count topic;
and
select t.id,comments.count topic left join ( select count(c.id) count,c.topic_id comment c group topic_id ) comments on t.id = comments.topic_id
i know theres not information. wanted know when use subquery , joined subquery , whats difference between them.
thanks
this question, add third option (the more standard way of doing this):
select t.id, count(c.topic_id) count topic left join comment c on t.id = c.topic_id group t.id;
the first way efficient in mysql. mysql can take advantage of index on comment(topic_id)
generate count. may true in other databases well, particularly noticeable in mysql not use indexes group by
in practice.
the second query aggregation , join. subquery materialized, adding additional overhead, , join
cannot use index on comment
. possibly use index on topic
, left join
may make option less likely. (you need check execution plan in environment.)
the third option equivalent first in many databases, not in mysql. join comment
(taking advantage of index on comment(topic_id)
, if available). however, incurs overhead of file sort final aggregation.
reluctantly, must admit first choice best in terms of performance in mysql, particularly if right indexes available. without indexes, of 3 might best choice. instance, without indexes, second best if comments
empty or has few topics.
Comments
Post a Comment