首页 > 解决方案 > 具有“OR”条件的 MySQL 优化连接查询

问题描述

我有一个数据库,其中包含 50 万个公司简介 + 他们提供服务的位置。所以我有公司表 + 位置表。公司可以服务于全国,也可以只服务于一个城市。位置表如下所示:

ID | company_id       | scope     | country_id | city_id
1  | 'companyuuid...' | 'city'    | 'UK'       | '32321'
2  | 'companyuuid...' | 'country' | 'US'       | NULL

当公司在全国范围内提供服务时,我们表示范围“国家”,当公司仅在特定城市内提供服务时,我们有范围“城市”。

不幸的是,当 MySQL 有“OR”语句并考虑到我们需要处理的数据量时,MySQL 处理查询的速度非常慢,因此应该尽可能优化查询。

select distinct companies.id from companies

inner join locations on companies.id = locations.company_id
and (locations.scope = 'city' and locations.city_id = '703448' ) 

order by companies.score desc limit 12 offset 0

我现在的问题是,在一个城市内搜索公司的时候,我还需要展示在全国范围内提供服务的公司。明显的方法是添加这样的 OR 语句:

select distinct companies.id from companies

inner join locations on companies.id = locations.company_id
and (locations.scope = 'city' and locations.city_id = '703448' ) 
or (locations.scope = 'country' and locations.country_id = 'UK' ) 
order by companies.score desc limit 12 offset 0

但问题是 OR 语句会使查询变得非常慢。有没有其他方法可以使用附加连接,所以我们可以保持快速查询?

标签: mysqlsqloptimizationentity-attribute-value

解决方案


问题1: OR似乎“错误”。你想要英国的所有城市,加上所有的伦敦,包括加拿大的一个。

您可能想要AND而不是OR. 你需要一个“自我加入”才能达到locations两次?EAV 架构很烂。

问题2: x AND y OR z(x AND y) OR z,不是x AND (y OR z)


推荐阅读