使用带有表语句的Select联接的SQL支持吗?例如,我们可以说
SELECT 1,2,3
a 没有表引用,并获得包含这些值的结果集。但是,有没有一种方法可以使用JOIN或CROSS JOIN并获得没有表引用的结果?例如,是否存在某些语法允许2个数字列表之间的交叉连接,从而返回2个列表的笛卡尔积,而无需引用任何表?
答案 0 :(得分:2)
是的,您可以将其放入带有别名的子查询中。然后加入。
例如,这适用于MS Sql Server,MySql,PostgreSql
SELECT *
FROM (SELECT 1 x,2 y ,3 z) n
CROSS JOIN (SELECT 'x' AS "1", 'y' AS "2", 'z' AS "3") ch;
在Oracle中,您必须包含一个FROM DUAL
。
SELECT *
FROM (SELECT 1 x,2 y ,3 z FROM DUAL) n
CROSS JOIN (SELECT 'x' AS "1", 'y' AS "2", 'z' AS "3" FROM DUAL) ch;
关于MS Sql Server,我在SO答案中注意到的更多是VALUES
技巧。
SELECT *
FROM (VALUES(1,2,3),(4,5,6)) AS n(x,y,z)
CROSS APPLY (VALUES('x','y','z')) AS ch([1],[2],[3]);
您可以在妊娠期here对其进行测试。
答案 1 :(得分:2)
是的,您可以使用派生表来做这种事情。
select *
from
(
select 1 as ID
UNION
select 2 as ID
UNION
select 3 as ID
) t
cross join
(select 5 as ID2
UNION
select 6 as ID2
) t2
答案 2 :(得分:1)
它可以/可以,但是,为什么是更大的问题。
select *
from (select 1 a,2 b,3 c) a
join (select 1 d,2 e,3 f) b on 1=1
select *
from (select 1 a,2 b,3 c) a
cross join (select 1 d,2 e,3 f) b
答案 3 :(得分:1)
也许您正在寻找:
racer_test=> \d
List of relations
Schema | Name | Type | Owner
--------+-----------------------+----------+--------
public | flyway_schema_history | table | jeeves
public | users | table | jeeves
public | users_id_seq | sequence | jeeves
(3 rows)
结果:
SELECT x1.n,
x2.n
FROM (SELECT 1 n
UNION ALL
SELECT 2 n
UNION ALL
SELECT 3 n) x1
CROSS JOIN (SELECT 1 n
UNION ALL
SELECT 2 n
UNION ALL
SELECT 3 n) x2;
答案 4 :(得分:0)
请注意,没有FROM的SELECT是非标准SQL。
在标准SQL中,无需表引用即可“生成”某些值的唯一方法是使用values()
子句:
select *
from ( values (1,2,3) ) as t(c1,c2,c3);
那当然可以与任何类型的联接相结合
select *
from ( values (1,2,3) ) as t1(c1,c2,c3)
cross join (values (3,4,5) ) as t2(x1,x2,x3);
将返回:
c1 | c2 | c3 | x1 | x2 | x3
---+----+----+----+----+---
1 | 2 | 3 | 3 | 4 | 5
或外部联接:
select *
from (
values (1,100),
(2,200),
(3,300)
) as t1(t1id,t2val)
left join (
values (1,42),
(2,24)
) t2 (t2id,t2val) on t1.t1id = t2.t2id;
返回:
t1id | t2val | t2id | t2val
-----+-------+------+------
1 | 100 | 1 | 42
2 | 200 | 2 | 24
3 | 300 | |