来自相关“访问”表的MySQL COUNT(*)

时间:2012-06-06 21:50:11

标签: mysql

我一直在研究MySQL查询,并想知道是否有更好的方法来做到这一点(没有相关的子查询等)。有问题的查询是

SELECT 
   (SELECT COUNT(*) as num_visits FROM visit WHERE data_type='gallery'
    and gallery.id=visit.object_id) as num_visits, gallery.id
FROM gallery
    ORDER BY num_visits desc

表结构的相关部分是

gallery
-------
id

visit
-----
id
data_type --> enum('gallery','etc')
object_id --> ties to various tables

对此的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

   SELECT COUNT(v.object_id) as num_visits, g.id
     FROM gallery g
LEFT JOIN visit v ON g.id=v.object_id AND v.data_type='gallery'
 GROUP BY g.id
 ORDER BY num_visits DESC

但更好的解决方案(从绩效角度来看)是预先计算并存储在gallery表(或其他一些)中的访问量