INNER JOIN与LIMIT版本相比

时间:2014-06-23 20:49:45

标签: sql join optimization

在我的第一个问题Multi-Table join need max version for each side中,我正在使用INNER JOIN来合并两个具有'版本'需要遵守的列。我的问题是 - 在使用LIMIT 1的外部查询结束时,这与ORDER BY version之间的区别是什么?会更快吗?它甚至以同样的方式工作吗?

 SELECT t1.*, t2.*
 FROM (SELECT t1.*
         FROM t1 ORDER BY t1.id, t1.version LIMIT 1) t1
 LEFT JOIN (SELECT t2.* FROM t2 ORDER by t2.id, t2.version LIMIT 1) t2 
    ON t2.id = t1.ruleId;

2 个答案:

答案 0 :(得分:1)

您的查询可能无法返回正确的结果。

首先,您可能希望使用DESC来获取MAX版本:

 SELECT t1.*, t2.*
 FROM (SELECT t1.*
         FROM t1 ORDER BY t1.id, t1.version DESC LIMIT 1) t1
 LEFT JOIN (SELECT t2.* FROM t2 ORDER by t2.id, t2.version DESC LIMIT 1) t2 
    ON t2.id = t1.ruleId;

但即使有这种修正,也会出现无法匹配的情况。

以这种情况为例:

t1:
id ruleid version
1  1      1
1  2      2
2  1      1
2  2      2
2  3      3

您对t1的子查询将选择此行:

SELECT t1.* FROM t1 ORDER BY t1.id, t1.version DESC LIMIT 1

t1:
id ruleid version
1  2      2

它将始终为id = 1返回一行。即使您使用#3和版本#100添加ID,LIMIT子句也会根据您的ORDER BY t1.id, t1.version DESC子句限制选择

现在,让我们检查一下t2。为了使t2具有这些值:

t2:
id version
1  1
1  2
2  1
2  2
2  3

子查询将选择此行:

SELECT t2.* FROM t2 ORDER by t2.id, t2.version DESC LIMIT 1

t2:
id version
1  2

如您所见,t2.id不会与t1.ruleid

一起加入

作为对上一个问题的回答而提出的查询:

SELECT t1.*, t2.*
 FROM (SELECT t1.*
         FROM t1
         JOIN (SELECT id, MAX(version) AS "VERSION"
                 FROM t1
                GROUP BY id) MAX_T1  ON MAX_T1.id = t1.id 
                                    AND MAX_T1.version = t1.version
      ) t1
 LEFT JOIN (SELECT t2.*
              FROM t2
              JOIN (SELECT t2.id, MAX(t2.version) AS "VERSION"
                      FROM t2
                     GROUP BY t2.id) MAX_T2  ON MAX_T2.id = t2.id 
                                            AND MAX_T2.version = t2.version
           ) t2 ON t2.id = t1.ruleId
;

将返回正确的匹配:t2.id将匹配t1.ruleid

顺便说一下,您只能将查询用于“已知”ID。例如。如果您需要为ID = 3选择最大版本,查询将如下所示:

 SELECT t1.*, t2.*
 FROM (SELECT t1.*
         FROM t1 WHERE ruleid=3 ORDER BY t1.id, t1.version DESC LIMIT 1) t1
 LEFT JOIN (SELECT t2.* FROM t2 WHERE id=3 ORDER by t2.id, t2.version DESC LIMIT 1) t2 
    ON t2.id = t1.ruleId
 WHERE t2.id = 3;

答案 1 :(得分:-1)

你想要最新的t1及其最新的t2。正确?

SELECT t1.*, t2.*
FROM       t1
INNER JOIN t2 on t2.id = t1.ruleId
ORDER BY t1.version DESC, t2.version DESC
LIMIT 1