【发布时间】:2019-04-04 14:39:08
【问题描述】:
我是新手,在使用 OR 查询时遇到问题!
当我不使用 OR 时,执行时间为:0.02 秒
SELECT DISTINCT p.*,
ht.html_title,
ht.html_content,
sc.sub_cat_name,
sc.main_cat_id,
us.username,
c.name AS cityname
FROM ad_product p,
ad_html ht,
ad_catagory_sub sc,
ad_user us,
ad_cities c
WHERE ( ht.ad_id = p.id )
AND ( sc.sub_cat_id = p.category )
AND ( us.id = p.user_id )
AND ( p.category = 216 )
AND ( p.status = 'active' )
AND ( c.id = p.city )
AND ( p.city = 135 )
ORDER BY p.created_at DESC;
当我尝试使用 OR 条件时,大约需要 4.70 秒
SELECT DISTINCT p.*,
ht.html_title,
ht.html_content,
sc.sub_cat_name,
sc.main_cat_id,
us.username,
c.name AS cityname
FROM ad_product p,
ad_html ht,
ad_catagory_sub sc,
ad_user us,
ad_cities c
WHERE ( ht.ad_id = p.id )
AND ( sc.sub_cat_id = p.category )
AND ( us.id = p.user_id )
AND ( p.category = 216
OR p.parent_category = 216 )
AND ( p.status = 'active' )
AND ( c.id = p.city )
AND ( p.city = 135 )
ORDER BY p.created_at DESC;
解释:
+----+-------------+-------+------------+-------------+--------------------------------------------------------------------------------+--------------------------+---------+---------------------------+-------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------------+--------------------------------------------------------------------------------+--------------------------+---------+---------------------------+-------+----------+----------------------------------------------------+
| 1 | SIMPLE | c | NULL | const | PRIMARY | PRIMARY | 4 | const | 1 | 100.00 | Using temporary; Using filesort |
| 1 | SIMPLE | p | NULL | index_merge | PRIMARY,id,parent_category,city,user_id_2,category,status,id_2,id_3,category_2 | category,parent_category | 4,4 | NULL | 67889 | 4.74 | Using union(category,parent_category); Using where |
| 1 | SIMPLE | sc | NULL | eq_ref | PRIMARY | PRIMARY | 4 | abc_classified.p.category | 1 | 100.00 | NULL |
| 1 | SIMPLE | us | NULL | eq_ref | PRIMARY | PRIMARY | 4 | abc_classified.p.user_id | 1 | 100.00 | NULL |
| 1 | SIMPLE | ht | NULL | ref | ad_id | ad_id | 4 | abc_classified.p.id | 1 | 100.00 | NULL |
+----+-------------+-------+------------+-------------+--------------------------------------------------------------------------------+--------------------------+---------+---------------------------+-------+----------+----------------------------------------------------+
我想我已经定义了正确的索引,有人可以指出我做错了什么吗?或者我怎样才能减少执行时间?另外,据我所知,为什么会发生这种情况?
【问题讨论】:
-
请将您的查询格式化为多行,以便我们阅读。
-
union解决方案应该可以工作,顺便说一句,您可以调用两个表p,无需将顶部查询更改为 p1。
标签: mysql sql performance conditional-statements