简体   繁体   中英

Django generates slow queries for OR clause (left outer join instead of union)

I have the following two models

class Video(models.Model):
    name = models.CharField(max_length=200)

class Store(models.Model):
    name = models.CharField(max_length=200)
    videos = models.ManyToManyField('Video')

Now I make the following queryset and print its query

qs = Video.objects.filter(Q(store__name="blockbuster") | Q(pk__in=[1,2,3,4]))
print qs.query

The following query is generated.

SELECT `video`.`id`, `video`.`name`,  
FROM `video` LEFT OUTER JOIN `store` ON (`store`.`video_id` = `video`.`id`) 
WHERE (`store`.`name` = "blockbuster"  OR `video`.`id` IN (1, 2, 3, 4))

When I do an explain plan on this query, mysql does a full table scan on the video table, despite adding every possible index. This is costing a me lot. How can I either force mysql to use an index or force django to use a UNION ALL which is faster instead of 'OR'?

Add an index for store_name,

name = models.CharField(max_length=200, db_index=True)

EDIT:

can you document any existing indices via:

show index from video;
show index from store;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM