当结果插入 HSQLDB 表时,如何对结果进行排序?

Posted

技术标签:

【中文标题】当结果插入 HSQLDB 表时,如何对结果进行排序?【英文标题】:How can I order the results as they are inserted into a HSQLDB table? 【发布时间】:2011-11-17 04:56:02 【问题描述】:

当我使用 HSQLDB 运行以下脚本时,我收到错误消息 user lacks privilege or object not found: T2C1。如何在将行插入表TABLE3 时对其进行排序?我可以在不添加另一个表的情况下实现此目标吗?

请注意,如果我评论 ORDER BY "T2C1", "T1C2" 行,我不会收到任何错误消息,但 TABLE3 也不会得到排序。

DROP TABLE "PUBLIC"."TABLE1" IF EXISTS;

CREATE TABLE "PUBLIC"."TABLE1" (
  "C1" VARCHAR(10),
  "C2" VARCHAR(10),
  "C3" VARCHAR(10)
);

INSERT INTO "PUBLIC"."TABLE1" ("C1", "C2", "C3") VALUES ('a', 'b', 'c');
INSERT INTO "PUBLIC"."TABLE1" ("C1", "C2", "C3") VALUES ('d', 'e', 'f');

DROP TABLE "PUBLIC"."TABLE2" IF EXISTS;

CREATE TABLE "PUBLIC"."TABLE2" (
  "C1" VARCHAR(10),
  "C2" VARCHAR(10),
);

INSERT INTO "PUBLIC"."TABLE2" ("C1", "C2") VALUES ('a', 'b');
INSERT INTO "PUBLIC"."TABLE2" ("C1", "C2") VALUES ('u', 'v');

DROP TABLE "PUBLIC"."TABLE3" IF EXISTS;

CREATE TABLE "PUBLIC"."TABLE3" (
  "C1" VARCHAR(10),
  "C2" VARCHAR(10),
);

INSERT INTO "PUBLIC"."TABLE3" (
  "C1",
  "C2"
)
SELECT 
(SELECT
"T2"."C1" AS "T2C1"
FROM "PUBLIC"."TABLE2" "T2"
WHERE "T2"."C1" = "T1"."C1"),
"T1"."C2" AS "T1C2"
FROM "PUBLIC"."TABLE1" "T1"
ORDER BY "T2C1", "T1C2"
;

* *DSV_COL_DELIM=,
* *DSV_ROW_DELIM=\n
* *DSV_TARGET_FILE=results.csv

\x "PUBLIC"."TABLE3"

【问题讨论】:

【参考方案1】:

HSQLDB 2.2.x 支持在此处使用 ORDER BY。 SELECT 的问题是标量子查询缺少列别名 T2C1。试试这个:

INSERT INTO "PUBLIC"."TABLE3" (
  "C1",
  "C2"
)
SELECT 
(SELECT
"T2"."C1" AS "T2C1"
FROM "PUBLIC"."TABLE2" "T2"
WHERE "T2"."C1" = "T1"."C1") AS T2C1,
"T1"."C2" AS "T1C2"
FROM "PUBLIC"."TABLE1" "T1"
ORDER BY "T2C1", "T1C2"
;

【讨论】:

【参考方案2】:

这对我来说没有多大意义,因为插入的顺序与其他人已经在各个论坛上提到的无关:

http://www.dbforums.com/microsoft-sql-server/1617505-insert-into-order.html http://social.msdn.microsoft.com/Forums/en/transactsql/thread/aeb1053d-0dc2-4dc3-96f5-8b213fed9669

我认为 HSQLDB 只是给出了错误的错误信息。它不适用于 MSSQL。

【讨论】:

以上是关于当结果插入 HSQLDB 表时,如何对结果进行排序?的主要内容,如果未能解决你的问题,请参考以下文章

如何对查询结果进行排序

Grails投影忽略MongoDB的排序顺序

如何将查询结果插入本地数据库

测试通过 Mule JDBC 传输到嵌入式 HSQLDB 的插入,后续查询不返回任何结果

在 Oracle(11.2 之前)中:使用 cast(collect(...)) 时,如何对结果进行排序?

如何按 Oracle SQL IN() 子句中的值顺序对结果数据进行排序