优化SQL查询,其中多个左连接重复两次

时间:2013-01-08 23:46:42

标签: mysql

如果有人可以提供改进以下查询的建议,那么这将是最有用的。我不确定当我在许多情况下两次左连接以分离表时我如何能够改进。例如,我有一个位置左连接到用户表,一个位置左连接到图像库表。我不确定我是否可以从这个角度优化sql。现在很慢。我确保所有列都在所有连接和where语句上编制索引。

SELECT im.alias_title, im.title,im.guid_id, im.description, im.hits, im.show_comment, im.can_print,
 im.can_download, im.can_share, im.created_on, im.date_taken, im.approved, im.visible,
ad.address_line_1, ad.address_line_2, ad.town_village_city, ad.state_province_county, ad.postal_code, ad.other_address_detail, co.country,
geo.latitude, geo.longitude, geo.zoom, geo.yaw, geo.pitch,
c.make, c.model,
us.first_name, us.surname, uf.user_id, uf.real_name, uf.user_name, uf.gender, uf.description, uf.description, uf.buddy_icon_url, uf.first_taken_date, uf.first_date,
uf.time_zone_label, uf.time_zone_offset,
adf.address_line_1 as user_address_line_1, adf.address_line_2 as user_address_line_2, adf.town_village_city as user_town_village_city, adf.state_province_county as user_state_province_county, 
adf.postal_code as user_postal_code, adf.other_address_detail as user_other_address_detail, cof.country as user_country,
geof.latitude as user_geolocation_latitude, geof.longitude as user_geolocation_longitude, geof.zoom as user_geolocation_zoom, geof.yaw as user_geolocation_yaw, geof.pitch as user_geolocation_pitch,
im.alias_title = in_image_alias_title AS image_selected -- image selected
FROM image im
LEFT JOIN address ad ON im.address_id = ad.id
LEFT JOIN country co ON ad.country_id = co.id
LEFT JOIN geolocation geo ON im.geolocation_id = geo.id
LEFT JOIN camera c ON im.camera_id = c.id
INNER JOIN user us ON im.user_id = us.id
LEFT JOIN user_flickr uf ON us.id = uf.id
LEFT JOIN address adf ON uf.address_id =adf.id
LEFT JOIN country cof ON ad.country_id = cof.id
LEFT JOIN geolocation geof ON uf.geolocation_id = geof.id
WHERE (im.alias_title = in_image_alias_title OR im.user_id = user_id)
AND im.approved = in_image_approved 
AND im.visible = in_image_visible
AND (im.advertise_to <= NOW() OR im.advertise_to IS NULL)
ORDER BY image_selected DESC;

enter image description here

1 个答案:

答案 0 :(得分:0)

在讨论/聊天室之后,了解更多你想要做的事情......

在与where子句关联的组件上构建复合索引,以便可以应用所有部分,而不仅仅是第一个关键元素中的最佳部分。此外,通过从where子句中删除“alias_title”(因为您基于别名标题开始获取用户ID),这是一个在查询中需要更多考虑的冗余子句。

我会索引(user_id,approved,visible,advertise_to)

结果会在事物的方案中回归并且很小,所以你的最终“order by”子句对它的最终排序输出没有任何问题。