Mysql获取非空中的第一个空行

时间:2018-09-20 07:17:34

标签: mysql

我有这个表结构:

quiz_id   id    end_utc
 40       40    2018-09-15 23:59:59
 41       41    2018-09-15 23:59:59
 42       42    2018-09-15 23:59:59
NULL      43    2018-09-15 23:59:59
NULL      45    2018-09-15 23:59:59

我想获取第一个空行的ID,在这种情况下为43,我当前拥有的查询是这样的:

select DISTINCT answers.quiz_id as quiz_id, 
         id, 
        end_utc FROM quiz 
LEFT JOIN answers ON quiz.id = answers.quiz_id AND answers.is_active = 
1 AND answers.player_id = 1 WHERE contest_id = 2

如果我尝试AND quiz_id IS NULL,它将返回43和45,但是前三行丢失了。

感谢您的帮助。此外,对于SQL Server也有Top 1 *,但在MySQL中不起作用。

谢谢!

PS:

我们可以期望这样的输出吗?

 quiz_id      id    end_utc
 40       40    2018-09-15 23:59:59
 41       41    2018-09-15 23:59:59
 42       42    2018-09-15 23:59:59
NULL      43    2018-09-15 23:59:59

1 个答案:

答案 0 :(得分:1)

使用https://flutter.io/setup-windows/#system-requirements分别获得两种情况的结果。

尝试以下操作:

(
select DISTINCT answers.quiz_id as quiz_id, 
                id, 
                end_utc 
FROM quiz 
INNER JOIN answers ON quiz.id = answers.quiz_id 
                     AND answers.is_active = 1 
                     AND answers.player_id = 1 
WHERE contest_id = 2 
ORDER BY answers.id ASC 
)

UNION ALL 

(
select DISTINCT answers.quiz_id as quiz_id, 
                id, 
                end_utc 
FROM quiz 
LEFT JOIN answers ON quiz.id = answers.quiz_id 
                     AND answers.is_active = 1 
                     AND answers.player_id = 1 
WHERE contest_id = 2 
  AND answers.quiz_id IS NULL 
ORDER BY answers.id ASC LIMIT 1
)

ORDER BY id ASC