首页 新闻 会员 周边

一个mysql语句的优化

0
悬赏园豆:10 [已解决问题] 解决于 2024-02-05 09:47

SELECT count(DISTINCT(p.CollectionID))
FROM location_photo t,photo p
where t.PhotoID = p.ID
AND t.LocationID in
(
SELECT children from location_structure
)

photo表上千万条数据
location_photo表上百万条数据
location_structure一千条左右数据
location_photo 的LocationID 有索引但是使用in索引失效
photo 表的ID和location_photo 表的PhotoID 都有索引
photo表的CollectionID无索引(最好不要加)

把in换成=,0.001秒就出结果了
但是用in,两分钟还没查出来

问题补充:

由于外面是大表里面是小表,不适合将in换成exists

teagueli的主页 teagueli | 初学一级 | 园豆:75
提问于:2019-04-28 17:56
< >
分享
最佳答案
0
SELECT
    COUNT(DISTINCT (p.CollectionID)) 
FROM
    (SELECT LocationID, PhotoID FROM location_photo) t
    INNER JOIN (SELECT ID, CollectionID FROM photo) p ON t.PhotoID = p.ID
    INNER JOIN location_structure s ON s.children = t.LocationID
收获园豆:10
大志若愚 | 老鸟四级 |园豆:2138 | 2019-04-29 15:13
其他回答(2)
0

你这个基本上没有太大的变化。为什么会很慢呢?是不是distinct 一定要用上吗? photo里面不唯一吗?
select count(distinct p.CollectionID) from photo p
where p.ID in (select t.photoId from location_photo where locationID in (select children from location_structure))

gw2010 | 园豆:1487 (小虾三级) | 2019-05-06 13:54
0

问题已经解决了

teagueli | 园豆:75 (初学一级) | 2024-02-05 09:35
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册