当前位置:  开发笔记 > 编程语言 > 正文

Union使用限制postgresql返回不同的输出

如何解决《Union使用限制postgresql返回不同的输出》经验,为你挑选了1个好方法。

我必须根据难度级别从我的问题集中提取12个问题.以下是我写的查询.

(SELECT q.question_text, q.option_a, q.option_b, q.option_c, q.option_d,
        q.correct_answer, q.image_link, q.question_type
        FROM questions_bank q
        JOIN sports_type st ON st.id = q.sports_type_id
        JOIN difficulty_level dl ON dl.id = q.difficulty_level_id
        WHERE st.game_type = LOWER('cricket') AND dl.value = 'E'
        ORDER BY random()
        LIMIT 7) 
UNION 
(SELECT q.question_text, q.option_a, q.option_b, q.option_c, q.option_d,
        q.correct_answer, q.image_link, q.question_type
        FROM questions_bank q
        JOIN sports_type st ON st.id = q.sports_type_id
        JOIN difficulty_level dl ON dl.id = q.difficulty_level_id
        WHERE st.game_type = LOWER('cricket') AND dl.value = 'M'
        ORDER BY random()
        LIMIT 4)
UNION 
(SELECT q.question_text, q.option_a, q.option_b, q.option_c, q.option_d, 
        q.correct_answer, q.image_link, q.question_type
        FROM questions_bank q
        JOIN sports_type st ON st.id = q.sports_type_id
        JOIN difficulty_level dl ON dl.id = q.difficulty_level_id
        WHERE st.game_type = LOWER('cricket') AND dl.value = 'H'
        ORDER BY random()
        LIMIT 1);

问题是每当我运行这个查询时,每次它给我一个不同数量的结果而不是静态12.有时我得到12,有时10,有时是15.我期望输出12行,而不是更少,不是更多.

这个查询有什么问题?



1> Clodoaldo Ne..:

可以使用窗口函数将其缩减为单个选择:

select *
from (
    select
        row_number() over (partition by dl.value order by random()) as rn,
        dl.value,
        q.question_text, q.option_a, q.option_b, q.option_c, q.option_d,
        q.correct_answer, q.image_link, q.question_type
    from
        questions_bank q
        inner join
        sports_type st on st.id = q.sports_type_id
        inner join
        difficulty_level dl on dl.id = q.difficulty_level_id
    where st.game_type = lower('cricket') and dl.value in ('E','M','H')
) s
where 
    value = 'E' and rn <= 7 or
    value = 'M' and rn <= 4 or
    value = 'H' and rn = 1

推荐阅读
喜生-Da
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有