SQLite:... EXCEPT ... ORDER BY RANDOM()

时间:2015-07-19 11:13:16

标签: sqlite random sql-order-by sql-except

此查询:

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 an sqlite table。有人可以解释为什么我的查询不起作用吗?

1 个答案:

答案 0 :(得分:1)

compound query中,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;