如何重写“选择顶部x子查询”#39;使用连接?

时间:2016-01-18 23:14:11

标签: sql ms-access join rewrite

我有一个查询,我使用子查询,我想重写为一个连接,以获得更好的性能。 (ms访问)

那么如何重写这样的查询才能使用join:

SELECT t.StudentID, t.subject, t.testid, t.TestScore, t.ID
FROM MyTable AS t
WHERE (((t.[TestID]) In (SELECT TOP 2 testid
                         FROM MyTable
                         WHERE StudentID = t.StudentID 
                         AND subject = t.subject
                         ORDER BY TestScore asc, testid)))
ORDER BY t.StudentID, t.TestScore, t.testID;

就像戈登·林诺夫所说的那样,如果不能轻易地将其改写为连接语法,那么'不是'? 这也难以重写为连接语法吗? 另外,仅供参考,我使用MS访问。

SELECT t.StudentID, t.subject, t.testid, t.TestScore, t.ID
FROM MyTable AS t
WHERE t.TestID not In (SELECT TOP 2 testid
                       FROM MyTable
                       WHERE StudentID = t.StudentID 
                       AND subject = t.subject
                       ORDER BY TestScore asc, testid)))
ORDER BY t.StudentID, t.TestScore, t.testID;

1 个答案:

答案 0 :(得分:0)

您无法(轻松)重写此查询以使用join。相反,您可以添加索引。

此查询的最佳索引是MySQL(StudentId, subject, TestScore, testid)