SQLite:...除了...按随机数排序()

nafvub8i  于 2022-11-14  发布在  SQLite
关注(0)|答案(1)|浏览(226)

此查询:

SELECT colour FROM ColourView
EXCEPT SELECT colour FROM SkinColourExceptionsView
WHERE race = 'Human' ORDER BY RANDOM() LIMIT 1

生成以下异常:

1st ORDER BY term does not match any column in the result set

但是,将ORDER BY RANDOM()更改为ORDER BY colour可以产生结果(按颜色字母顺序排序,而不是随机排序)。
下面建议ORDER BY RANDOM() LIMIT 1应该可以工作:Select random row from a sqlite table
有人能解释一下为什么我的查询不起作用吗?

rlcwz9us

rlcwz9us1#

在复合查询中,ORDER BY术语必须与结果集中的某个列匹配。
您可以通过将复合查询移入子查询来绕过此限制:

SELECT colour
FROM (SELECT colour FROM ColourView
      EXCEPT
      SELECT colour FROM SkinColourExceptionsView WHERE race = 'Human')
ORDER BY random()
LIMIT 1;

或者,重写查询以使用不同的筛选机制:

SELECT colour
FROM ColourView
WHERE colour NOT IN (SELECT colour
                     FROM SkinColourExceptionsView
                     WHERE race = 'Human')
ORDER BY random()
LIMIT 1;

相关问题