2013-01-08 79 views
0

如果有人可以就改善以下查詢提供建議,這將是最有用的。我無法確定如何在許多情況下左連接兩次以分開表格時如何進行改進。例如,我有一個位置左連接到用戶表和一個位置左連接到圖像庫表。我不確定是否可以從這個角度優化sql。目前速度非常緩慢。我已確保所有列都在所有連接和聲明處編制索引。優化多個左連接重複兩次的SQL查詢

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

+0

好吧,你真的*需要所有這些表中的所有列嗎? –

+0

是的需要他們在圖像頁面上。 –

+0

在查詢上運行EXPLAIN。 –

回答

0

討論/聊天室後,學習更多的東西,你試圖做...

建立與您的where子句,因此所有相關的成分的複合索引部件可以應用,而不僅僅是第一個關鍵要素中的最好部分。另外,通過從where子句中刪除「alias_title」(因爲您以開始的別名標題獲取用戶標識),這是一個冗餘子句,在查詢中佔用更多的注意。

我將在(USER_ID,批准,可見,advertise_to)指數

結果會回來,並在對事物的計劃少,所以你最終的「排序依據」條款將與它的最終沒問題排序輸出。