mysql查询优化not in_mysql – 如何优化这个“IN”和“where NOT IN”查询?

以下查询/查询获取用户访问过的城市,获取用户访问过的地点;并返回用户尚未进入的城市中的地点.

// I get the city_id and object_id. Each vote has the place_id and its city_id.

SELECT DISTINCT city_id as city_id, object_id as object_id

FROM vote

WHERE object_model = 'Place'

AND user_id = 20

ORDER BY created_at desc

// I build an array with city_ids and another with object_ids

$city_ids = array(...);

$place_ids = array(...);

我得到了用户未去过的城市的地方 – 1秒钟

SELECT id, title

FROM place

WHERE city_id IN ($city_ids)

AND id NOT IN ($place_ids)

ORDER BY points desc

LIMIT 0,20

EXPLAIN SQL

select_type table type possible_keys key key_len ref ows Extra

-----------------------------------------------------------------------------------------------------------

SIMPLE p range PRIMARY,city_id_index city_id_index 9 NULL 33583 Using where; Using filesort

另一个优化尝试是使用LEFT JOIN / IS NULL和子查询进行一次查询,但需要更长的时间(30秒)

SELECT id, title

FROM place AS p

LEFT JOIN vote v ON v.object_id = p.id

AND v.object_model = 'Place'

AND v.user_id = 20

WHERE p.city_id IN (SELECT city_id

FROM vote

WHERE user_id = 20

AND city_id != 0)

AND v.id is null

ORDER BY p.points desc

LIMIT 0, 20

您如何进行查询/查询,以确定每个用户可以拥有500个城市和1000个地方的数组?当有许多ID时,哪个是哪个地方以及哪里不是IN的最佳替代方案?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值