SQL - 按顺序查找下一行ID

时间:2014-06-11 10:39:23

标签: mysql sequence next

我有两个表TESTS和TESTS_ATTEMPTED。我正在尝试为给定的USER_ID输出要在每种测试类型(数学,英语,科学)中进行的下一个测试的ID。

表的结构如下(带有一些样本数据):

TESTS
================
 ID    TEST_NAME   TEST_TYPE
  1     Science 1   Science
  2     Maths 1     Maths
  3     Maths 2     Maths
  4     Science 2   Science

TESTS_ATTEMPTED
================
ID   TEST_ID   USER_ID 
 1     1          2 
 2     1          1 
 3     2          2  
 4     3          2  

这个虚拟数据的SQL小提琴在这里:http://www.sqlfiddle.com/#!2/43efb/2

预期结果是(对于用户ID 2):

TEST_TYPE   NUM_TESTS   NUM_TAKEN   NEXT_TEST_ID    
Science       2            1         4
Maths         2            2         Null

我能够创建一个查询,其中包含用户所进行的测试次数,但不确定是否可以输出下一个测试类型?

SELECT count(*) as num_tests_taken, 
    TEST_NAME from TEST_NAMES tn 
INNER JOIN TESTS_ATTEMPTED ta on tn.ID = ta.TEST_ID AND ta.USER_ID = 2 
GROUP BY tn.ID

我如何将查询一起加入并输出下一个TEST ID?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

SELECT TEST_TYPE, COUNT(*) AS NUM_TESTS, COUNT(TEST_ID) AS NUM_TAKEN, (
        SELECT MIN(tn.ID)
        FROM TESTS tn
        LEFT JOIN TESTS_ATTEMPTED ta ON tn.ID = ta.TEST_ID
            AND ta.USER_ID = 2
        WHERE otn.TEST_TYPE = tn.TEST_TYPE
            AND ta.USER_ID IS NULL
        GROUP BY TEST_TYPE
        ) AS NEXT_TEST_ID
FROM TESTS otn
LEFT JOIN TESTS_ATTEMPTED ota ON otn.ID = ota.TEST_ID
    AND ota.USER_ID = 2
GROUP BY TEST_TYPE