如何在具有百万行的大型数据库表上优化此查询

时间:2015-06-09 18:43:57

标签: mysql query-optimization

SELECT l.player_id,game_group_type,game_type,no_of_card,room_group_type,device_type 
FROM rummy_player_login_master k 
JOIN 
(

        SELECT no_of_card,game_group_type,game_type,room_group_type,player_id,login_id 
        FROM rummy_game_type_master i 
        JOIN 
        (
            SELECT  game_type_id,  room_group_type,player_id,login_id 
            FROM rummy_room_group_master g 
            JOIN 
            ( 
                SELECT room_group_id ,player_id,login_id 
                FROM rummy_room_domain_group_mapping e  
                JOIN 
                (
                    SELECT  common_id,player_id,login_id 
                    FROM rummy_room_master c 
                    JOIN 
                    (
                        SELECT room_id ,player_id,login_id 
                        FROM rummy_room_session_master a 
                        JOIN  
                        (
                            SELECT MAX(session_id) AS session_id,player_id,login_id 
                            FROM rummy_room_session_player_mapping 
                            GROUP BY player_id 
                        ) b 
                        ON a.session_id = b.session_id 
                    ) d 
                    ON c.room_id = d.room_id
                ) f 
                ON e.common_id =f.common_id
            ) h 
            ON g.room_group_id = h.room_group_id
        ) j 
        ON i.game_type_id = j.game_type_id

) l 
ON k.login_id = l.login_id 
GROUP BY l.player_id

1 个答案:

答案 0 :(得分:0)

假设我弄清楚哪些列正确地转到了哪些表,这个查询应该是等价的(或者更好,因为你原来滥用了GROUP BY)。

SELECT 
rrspm.player_id,
rgtm.game_group_type,
rgtm.game_type,
rgtm.no_of_card,
rrgm.room_group_type,
rplm.device_type 
FROM rummy_room_session_player_mapping rrspm
LEFT OUTER JOIN rummy_room_session_player_mapping later_rrspm
ON later_rrspm.player_id = later_rrspm.player_id
AND later_rrspm.session_id > rrspm.session_id
INNER JOIN rummy_player_login_master rplm 
ON rrspm.login_id = rplm.login_id
INNER JOIN rummy_room_session_master rrsm 
ON rrsm.session_id = rrspm.session_id
INNER JOIN rummy_room_master rrm 
ON rrm.room_id = rrsm.room_id
INNER JOIN rummy_room_domain_group_mapping rrdgm
ON rrdgm.common_id = rrm.common_id
INNER JOIN rummy_room_group_master rrgm 
ON rrgm.room_group_id = rrdgm.room_group_id
INNER JOIN rummy_game_type_master rgtm
ON rgtm.game_type_id = rrgm.game_type_id
WHERE later_rrspm.session_id IS NULL

如果您仍需提高效果,请尝试以下操作:

ALTER TABLE rummy_room_session_player_mapping
ADD INDEX `player_session` (`player_id`,`session_id`)

原始查询中的语法看起来与我开始使用数据库时遇到的困难相同,因为您没有正确地查看基于设置的数据。

如果我的查询有效,我建议你研究我做了什么,并了解你不需要做所有那些嵌套选择来得到你想要的东西。数据库本身将按照所需的顺序放置内容,您只需要告诉它在哪些列上加入适当的表。