我在我的应用程序中进行以下查询,检索行:
SELECT
title,
SUBSTRING(description, 1, 200) AS s_description,
refresh_time, (UNIX_TIMESTAMP()-refresh_time) AS since,
state, state_friendly,
city, city_friendly,
category, category_friendly,
basename, COUNT(ad_id) AS im_ocur
FROM `ad` `a`
JOIN `state` ON state_id = ad_state_id
JOIN `city` ON city_id = ad_city_id
JOIN `category` ON category_id = ad_category_id
LEFT JOIN `ad_image` ON ad_image_ad_id = ad_id
WHERE (ad_country_id = 195)
GROUP BY `ad_id`
ORDER BY `refresh_time` DESC, front DESC
LIMIT 20
我在很多情况下测试了它,但是当提到一个有很多行的城市时,性能却降低了。经过几次更改后,我意识到问题是由于“(UNIX_TIMESTAMP() - refresh_time)”表达式所致,所以看起来Mysql Engine在行限制设置为20之前进行算术运算。
我的替代解决方案是使用PHP对数据进行后处理,但我更喜欢完整的mysql方式。
有可能吗?
答案 0 :(得分:0)
我认为这不是一个减法,但是为每一行调用了UNIX_TIMESTAMP()(虽然我可能错了)。
如果您认为减法是性能低下的原因,您可以随时将其移至外部查询。
SELECT
title,
s_description,
refresh_time, (UNIX_TIMESTAMP()-refresh_time) AS since,
state, state_friendly,
city, city_friendly,
category, category_friendly,
basename, im_ocur
FROM (
SELECT
title,
SUBSTRING(description, 1, 200) AS s_description,
refresh_time,
state, state_friendly,
city, city_friendly,
category, category_friendly,
basename, COUNT(ad_id) AS im_ocur
FROM `ad` `a`
JOIN `state` ON state_id = ad_state_id
JOIN `city` ON city_id = ad_city_id
JOIN `category` ON category_id = ad_category_id
LEFT JOIN `ad_image` ON ad_image_ad_id = ad_id
WHERE (ad_country_id = 195)
GROUP BY `ad_id`
ORDER BY `refresh_time` DESC, front DESC
LIMIT 20
) AS sq