Mysql组中的随机项和组中的计数项

时间:2013-05-25 14:49:41

标签: mysql optimization

enter image description here你好以下所有查询都很慢我似乎无法优化它。

我尝试了两种方法。两者都很慢。

我需要从每个image_tag中获取一个随机项,以及属于标签的图像数量。任何建议将不胜感激。查询两分钟执行任一方式。与图像计数和连接相关的速度较慢。图像计数本身非常快。在加入时很慢。

SELECT T.id, T.title, T.guid_id, T.hits, al.title, tt.title, tt.raw, it.tag_title_id
,((ACOS(SIN(53.38946 * PI() / 180) * SIN(geo.latitude * PI() / 180) + COS(53.38946 * PI() / 180) 
* COS(geo.latitude * PI() / 180) * COS((-2.599586 - geo.longitude) * PI() / 180)) * 180 / PI()) * 60 * 1.1515)
AS distance, uf.real_name, uf.user_name, itx.image_count
FROM 
     (SELECT imx.id, imx.guid_id,  imx.user_id, imx.approved, imx.hits, imx.title, imx.visible, imx.geolocation_id, imx.advertise_to
      FROM image imx
      ORDER BY floor(RAND()*(SELECT count(1) FROM image)))
      AS T
INNER JOIN image_tag it ON T.id = it.image_id 
INNER JOIN tag_title tt ON it.tag_title_id =tt.id
INNER JOIN album_image ai ON T.id = ai.image_id
INNER JOIN album al ON ai.album_id = al.id
INNER JOIN user us ON T.user_id = us.id
LEFT JOIN user_flickr uf ON us.flickr_id = uf.id
LEFT JOIN user_site uss ON us.user_site_id= uss.id
LEFT JOIN geolocation geo ON T.geolocation_id = geo.id
LEFT JOIN (SELECT image_id, count(*) as image_count FROM image_tag GROUP BY image_id) itx ON itx.image_id = T.id 
WHERE T.visible = in_image_visible
AND T.approved = in_image_approved
AND (T.advertise_to <= in_date_time_now OR T.advertise_to IS NULL)
GROUP BY tt.id;

这很快

SELECT * FROM (SELECT image_id, count(*) as image_count 
    FROM image_tag it
    GROUP BY image_id) T
INNER JOIN image im ON T.image_id = im.id

当我在连接上添加随机逻辑时,它非常慢

2 个答案:

答案 0 :(得分:0)

主要问题是您的查询中有两个filesorts超过20,000行。

这意味着您在没有索引的情况下进行排序,索引会很慢,而且速度很慢。

我建议你放弃随机排序...用你处理PHP结果的任何语言来做。那将删除其中一个filesorts。如果这可以使事情达到合理的水平,那就太好了。

答案 1 :(得分:0)

您可以尝试使用此方法获取随机图片:

  SELECT imx.id, imx.guid_id,  imx.user_id, imx.approved, imx.hits, imx.title, imx.visible, imx.geolocation_id, imx.advertise_to
  FROM image imx
  ORDER BY rand()

额外的子查询不能帮助解决问题。