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
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
你这个基本上没有太大的变化。为什么会很慢呢?是不是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))
问题已经解决了