以下查询在mySQL和Oracle中都运行良好:
select * from (
(select distinct msg_key from lct_messages where msg_step = 2) x,
(select distinct msg_step from lct_messages where msg_next_step = 3) y
)
其目的是在单独的列中的一行中获取两个值。你能帮助我将这个查询转换为将在Postgres中运行的查询吗?
当我运行下面的那个时,我收到错误:
SELECT (
(SELECT DISTINCT "MSG_KEY" FROM LCT_MESSAGES WHERE "MSG_STEP" = 2) x,
(SELECT DISTINCT "MSG_STEP" FROM LCT_MESSAGES WHERE "MSG_NEXT_STEP" = 3) y
)
此致 米甲
答案 0 :(得分:1)
你有一对额外的parens。这将两个结果组合成一个类型record
的单个结果列,创建记录对象的语法不允许像 1 那样定义记录列的别名。这就是为什么它在x
上因语法错误而窒息。
试试这个:
SELECT
(SELECT DISTINCT "MSG_KEY" FROM LCT_MESSAGES WHERE "MSG_STEP" = 2) x,
(SELECT DISTINCT "MSG_STEP" FROM LCT_MESSAGES WHERE "MSG_NEXT_STEP" = 3) y;
这给了我一个简单的虚拟表,这对我来说是正确的:
$ WITH LCT_MESSAGES ("MSG_KEY", "MSG_STEP", "MSG_NEXT_STEP") AS (VALUES
('a', 1, 2),
('b', 2, 3),
('c', 3, 4)
)
SELECT
(SELECT DISTINCT "MSG_KEY" FROM LCT_MESSAGES WHERE "MSG_STEP" = 2) x,
(SELECT DISTINCT "MSG_STEP" FROM LCT_MESSAGES WHERE "MSG_NEXT_STEP" = 3) y;
x | y
---+---
b | 2
(1 row)
1 有关您无意中使用的语法的说明,请参阅section 8.15.2 "Composite Value Input" of the PostgreSQL 9.1 documentation:" ROW
表达式语法也可用于构建复合值。 ...只要表达式中有多个字段,ROW关键字实际上是可选的..." 所以它看到的内容与此相同:
SELECT ROW(
(SELECT DISTINCT ...) x,
(SELECT DISTINCT ...) y
);
x
在这种表达式中确实是无效的语法。