如何找到HSQLDB中顺序编号的空白?

时间:2018-01-25 02:12:21

标签: sql hibernate hsqldb gaps-and-islands

我试图让this answer made for MySQL适应HSQLDB(2.4.0,通过Hibernate 5.2.12)。我已经取代了MySQL" IF"功能由" CASE WHEN"电话如下:

SELECT
 CONCAT(z.expected, CASE WHEN z.got-1>z.expected THEN CONCAT(' thru ',z.got-1) ELSE '' END) AS missing
FROM (
 SELECT
  @rownum\\:=@rownum+1 AS expected,
  CASE WHEN @rownum=id THEN 0 ELSE @rownum\\:=id END AS got
 FROM
  (SELECT @rownum\\:=0) AS a
  JOIN Notices
  WHERE fonds_cote = '1Fi'
  ORDER BY id
 ) AS z
WHERE z.got!=0;

转义:以避免来自Hibernate的解析错误。不过,它不起作用,我面对:

org.hsqldb.HsqlException: unexpected token: (
    at org.hsqldb.error.Error.parseError(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserBase.unexpectedToken(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserDQL.XreadSelect(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserDQL.XreadQuerySpecification(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserDQL.XreadSimpleTable(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserDQL.XreadQueryPrimary(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserDQL.XreadQueryTerm(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserDQL.XreadQueryExpressionBody(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserDQL.XreadQueryExpression(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserCommand.compilePart(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.ParserCommand.compileStatement(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.Session.compileStatement(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.StatementManager.compile(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.Session.execute(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source) ~[hsqldb-2.4.0.jar:2.4.0]
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]

正确的语法是什么?或者在HSQLDB中有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

问题是使用变量@rownum。 HSQLDB不支持此功能。

使用HSQLDB,您可以以简单的方式完成。

假设该表名为CUSTOMER,序列列称为ID。下面的查询显示了SEQUENCE_ARRAY的工作原理,并用于查找缺失值。

-- this returns consecutive numbers within a fixed range
SELECT * FROM UNNEST (SEQUENCE_ARRAY(1, 1000, 1))
-- this returns all the possible consecutive numbers for an existing table
SELECT * FROM UNNEST (SEQUENCE_ARRAY((SELECT MIN(ID) FROM CUSTOMER), (SELECT MAX(ID) FROM CUSTOMER), 1))

-- this returns the list of unused IDs.
SELECT * FROM UNNEST (SEQUENCE_ARRAY((SELECT MIN(ID) FROM CUSTOMER), (SELECT MAX(ID) FROM CUSTOMER), 1)) SEQ(IDCOL)
LEFT OUTER JOIN CUSTOMER ON CUSTOMER.ID = SEQ.IDCOL WHERE CUSTOMER.ID IS NULL