with子句

7nbnzgx9  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(324)

**结案。**此问题不可复制或由打字错误引起。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

9个月前关门了。
改进这个问题
使用with子句查询不同的表/模式

WITH T1 as ( SELECT something as s1 from schema1.table1 ),
WITH T2 as ( SELECT something as s2 from schema2.table1 )
SELECT * FROM T1,T2;

它给出的错误为:error:syntax error在“with”处或附近
你能指出我遗漏了什么吗

uajslkp6

uajslkp61#

这个 with 关键字只应在查询开头出现一次:

WITH 
    T1 as ( SELECT something as s1 from schema1.table1 ),
    T2 as ( SELECT something as s2 from schema2.table1 )
SELECT T1.something something1, T2.something something2
FROM T1
CROSS JOIN T2;

注意,我将隐式连接重写为显式连接 cross join . 您可能还应该在resultset中为列名起别名,因为两个查询都会生成一个名称相同的列。

nnsrf1az

nnsrf1az2#

你到底想要什么?
两个表的笛卡尔积
第一个表的所有行,第二个表的所有行?
我在with子句中放置了一些示例数据(是的,with关键字只有一次,然后是一个逗号列表),并显示了两个结果。你的,首先(我同意@gmb,你应该使用它) CROSS JOIN 如果将两个表连接起来(没有筛选器),那么我认为更有意义。
来吧。

-- the WITH clause ...
WITH
table1(id,something) AS (
          SELECT 11,'something 1 from 1'
UNION ALL SELECT 12,'something 2 from 1'
UNION ALL SELECT 13,'something 3 from 1'
)
,
table2(id,something) AS (
          SELECT 21,'something 1 from 2'
UNION ALL SELECT 22,'something 2 from 2'
UNION ALL SELECT 23,'something 3 from 2'
)

--然后,我从中选择,就像你会得到的结果一样:

SELECT * FROM table1,table2
 id |     something      | id |     something      
----+--------------------+----+--------------------
 11 | something 1 from 1 | 21 | something 1 from 2
 12 | something 2 from 1 | 21 | something 1 from 2
 13 | something 3 from 1 | 21 | something 1 from 2
 11 | something 1 from 1 | 22 | something 2 from 2
 12 | something 2 from 1 | 22 | something 2 from 2
 13 | something 3 from 1 | 22 | something 2 from 2
 11 | something 1 from 1 | 23 | something 3 from 2
 12 | something 2 from 1 | 23 | something 3 from 2
 13 | something 3 from 1 | 23 | something 3 from 2

--最后,我几乎肯定你应该做的是:

SELECT * FROM table1 UNION ALL SELECT * FROM table2;
  id |     something      
 ----+--------------------
  11 | something 1 from 1
  12 | something 2 from 1
  13 | something 3 from 1
  21 | something 1 from 2
  22 | something 2 from 2
  23 | something 3 from 2

相关问题