QUERY:
SELECT
(
SELECT COUNT(cleanpoi.ID) FROM cleanpoi
WHERE cleanpoi.EstablishmentID=parent.ID
) AS POIs,
(
SELECT COUNT(ID) FROM cleanamenitymappings WHERE CleanPOIID IN
(
SELECT cleanpoi.ID FROM cleanpoi
WHERE cleanpoi.EstablishmentID=parent.ID
)
) AS Amenities,
(
SELECT COUNT(ID) FROM cleanamenityvalues WHERE CleanPOIID IN
(
SELECT cleanpoi.ID FROM cleanpoi
WHERE cleanpoi.EstablishmentID=parent.ID
)
) AS AmenityValues
FROM establishment parent
WHERE parent.ID=3
分析结果:
id select_type table type possible_keys key key_len ref rows Extra
------ ------------------ -------------------- --------------- ----------------------------------------- --------------- ------- ------ ------ --------------------------
1 PRIMARY parent const PRIMARY PRIMARY 4 const 1 Using index
5 DEPENDENT SUBQUERY cleanamenityvalues ALL (NULL) (NULL) (NULL) (NULL) 31778 Using where
6 DEPENDENT SUBQUERY cleanpoi unique_subquery PRIMARY,EstablishmentID_2,EstablishmentID PRIMARY 4 func 1 Using where
3 DEPENDENT SUBQUERY cleanamenitymappings index (NULL) CleanPOIID 4 (NULL) 673591 Using where; Using index
4 DEPENDENT SUBQUERY cleanpoi unique_subquery PRIMARY,EstablishmentID_2,EstablishmentID PRIMARY 4 func 1 Using where
2 DEPENDENT SUBQUERY cleanpoi ref EstablishmentID_2,EstablishmentID EstablishmentID 4 const 181
对此查询有何建议?你的答案非常感谢!
答案 0 :(得分:0)
您的查询会扫描700k行,所有这些行都需要从磁盘中读取。我猜测磁盘性能不佳(带宽和/或寻道时间)。
如果经常运行此查询,请考虑创建一个实体化视图,该视图是一个表,其中包含整个查询的答案,以及在基础数据更改时使用触发器更新的表。
答案 1 :(得分:0)
我将使用中间结果创建临时表,然后从此临时表中进行选择。
创建存储过程可能很有用:
delimiter ;;
create procedure MyLongProcedure()
begin
-- Just in case, drop the temporary tables before creating them
drop table if exists temp_step01;
-- Make a temporary table for each subquery
create temporary table temp_step01
select ... ;
-- Be sure to create the appropriate indexes for each temporary table
alter table temp_step01
add index .... ;
-- Create as much tables as you need
-- Finally, execute your final query using all the tables you just created
select ... ;
end;;
delimiter ;
请记住:临时表只能通过创建它们的连接读取。在多用户环境中,根据您的具体需求,它是否有用。
这只是一个想法。希望它可以帮到你。
答案 2 :(得分:0)
感谢所有答案,但这解决了我的问题。
SELECT
(
SELECT COUNT(cleanpoi.ID) FROM cleanpoi
WHERE cleanpoi.EstablishmentID=parent.ID
) AS POIs,
(
SELECT COUNT(a.ID)
FROM cleanamenitymappings a LEFT JOIN cleanpoi b ON a.CleanPOIID=b.ID
WHERE b.EstablishmentID=parent.ID
) AS Amenities,
(
SELECT COUNT(a.ID)
FROM cleanamenityvalues a LEFT JOIN cleanpoi b ON a.CleanPOIID=b.ID
WHERE b.EstablishmentID=parent.ID
) AS AmenityValues
FROM establishment parent
WHERE parent.ID=3