我有需要连接5个表的sql查询。到目前为止,我已经尝试过此查询。 它正在工作,但需要很长时间。在这里可以做些什么来优化以下查询?
$select_query = 'select ';
$select_query .= "ROUND((
6371 * ACOS(
COS(RADIANS('.$lat.')) COS(RADIANS(lat)) COS(
RADIANS(lng) - RADIANS('.$lng.')
) + SIN(RADIANS('.$lat.')) * SIN(RADIANS(lat))
)
),2) AS property_distance ,";
$select_query .= "
pro.id as id,
pro.user_id,
pro.category_id,
pro.total_price,
pro.size,
pro.lat,
pro.lng,
pro.city,
pro.city_english,
pro.created_at,
pimg.image as property_images,
pimg.property_id,
pa.property_id,
pa.category_attribute_id,
pa.is_multiple_data,
pa.attribute_value,
ca.category_id,
ca.attribute_name,
ct.category_id,
ct.category_name,
cat.attribute_id,
cat.attribute_label,
cat.locale
FROM
property pro FORCE INDEX (property_index)
left join property_images pimg on pro.id=pimg.property_id
JOIN property_attributes pa ON
pa.property_id = pro.id
left JOIN category_attributes ca ON
ca.id = pa.category_attribute_id
left JOIN category_attributes_translations cat ON
ca.id = cat.attribute_id
left JOIN categories_translation ct ON
pro.category_id = ct.category_id
WHERE pro.is_confirm='1' and pro.status='1' and pro.deal_finish='0' and cat.locale='" . $locale . "' and ct.locale='" . $locale . "'
GROUP BY pro.id HAVING property_distance<=10 ORDER by pro.id DESC";
然后最终运行此查询。
请向我建议优化此查询的正确方法。
答案 0 :(得分:0)
在进行任何连接之前,我将修改查询以遍历属性表并消除尽可能多的行。大圆距离计算结果的HAVING子句中的条件将要求对每行进行计算,否则WHERE子句不会消除该行。
我只会针对property
表编写查询,如下所示:
SELECT ROUND( ( 6371 * ACOS( COS(RADIANS( :lat ) )
* COS(RADIANS(pro.lat))
* COS(RADIANS(pro.lng) - RADIANS( :lng ) )
+ SIN(RADIANS( :lat ))
* SIN(RADIANS(pro.lat))
)
)
,2) AS property_distance
, pro.id
, pro.user_id
, pro.category_id
, pro.total_price
, pro.size
, pro.lat
, pro.lng
, pro.city
, pro.city_english
, pro.created_at
FROM property pro
WHERE pro.is_confirm = '1'
AND pro.status = '1'
AND pro.deal_finish = '0'
HAVING property_distance <= 10
ORDER
BY pro.id DESC
这假设id
在property
表中是唯一的。这样应该可以有效地使用前导列为deal_finish
,status
和is_confirm
的索引,从而避免考虑某些行。
... ON property (deal_finish,status,is_confirm,...)
一旦有了该设置,就可以在外部查询中将其作为内联视图(派生表)引用,并且外部查询可以将其连接到其他表。
请注意,如果我们在product_images
和product_attributes
中有多个匹配的行,则对两个表进行联接都会创建一个半笛卡尔积,product_image
中的每一行都与之匹配product_attribute
中的行。即product_image
的20行与product_attribute
的20行交叉连接将产生一组400行。
SELECT c.*
FROM ( -- inline view query
SELECT ROUND( ( 6371 * ACOS( COS(RADIANS( :lat ) )
* COS(RADIANS(pro.lat))
* COS(RADIANS(pro.lng) - RADIANS( :lng ) )
+ SIN(RADIANS( :lat ))
* SIN(RADIANS(pro.lat))
)
)
,2) AS property_distance
, pro.id
, pro.user_id
, pro.category_id
, pro.total_price
, pro.size
, pro.lat
, pro.lng
, pro.city
, pro.city_english
, pro.created_at
FROM property pro
WHERE pro.is_confirm = '1'
AND pro.status = '1'
AND pro.deal_finish = '0'
HAVING property_distance <= 10
ORDER BY pro.id DESC
) c
LEFT
JOIN product_images pimg
ON pimg.product_id = c.id
ORDER BY c.id DESC
现在整个问题是使用GROUP BY
折叠行,并且表达式在功能上不依赖,例如ONLY_FULL_GROUP_BY sql_mode等。