每种类型的SQL JOIN都是CROSS JOIN的子集

时间:2014-02-02 12:52:25

标签: sql join subset cross-join

我想确认一下我对JOINS研究的理解。是每一个     SQL JOIN的类型是CROSS JOIN的子集?

CROSS JOIN您正在选择笛卡尔积,所以如果你有表A(100行)和
    表B(100行)得到100 x 100 = 10,000

所有其他JOINS并基本上从上面的集合中选择数据。

与INNER JOIN或仅JOIN类似,它只提供在一个上匹配的那些行     具体栏目。

LEFT OUTER JOIN给出左边的所有空行,包括INNER的内容 JOIN。

两个问题

  1. 是否可以加入多个列?假设我将2列组合在一起作为我的主键

  2. 我在想JOIN的结果并不依赖于表的关系?如果你在两个表之间有一对一,你的CROSS连接将产生/返回相同的行数。

1 个答案:

答案 0 :(得分:3)

每个类型的SQL连接都会返回交叉连接的正确子集。例如,对于与连接条件不匹配的列,左连接将返回NULL。但这些行不会出现在交叉连接中。使用PostgreSQL,

-- cross join . . .
with t1 as (
  select 1 as n, 'a' as s
  union all
  select 2, 'b'
), t2 as (
  select 1 as n, 'a' as s
)
select * 
from t1
cross join t2

1  a  1  a 
2  b  1  a

-- left outer join
with t1 as (
  select 1 as n, 'a' as s
  union all
  select 2, 'b'
), t2 as (
  select 1 as n, 'a' as s
)
select * 
from t1
left join t2 on t1.n = t2.n

1  a  1  a 
2  b

第二行不在交叉连接中。

是的,您可以加入多个专栏。

select your-column-list
from table_1 t1
inner join table_2 t2
        on t1.first_column  = t2.first_matching_column
       and t1.second_column = t2.second_matching_column

您也可以加入专栏的一部分,或加入不平等。

-- Joins the three-character column t1.first_column on the first
-- three characters of t2.first_matching_column. Exact syntax
-- depends on the DBMS, but most support something like this.
inner join table_2 t2
        on t1.first_column  = left(t2.first_matching_column, 3)

-- Joins on an inequality. Also called a non-equijoin or theta join.
inner join table_2 t2
        on t1.first_column  < t2.first_matching_column

并且连接不依赖于表之间的关系(外键引用)。联接仅依赖于常见(或兼容)值。在大多数情况下,如果连接列具有不同的数据类型,则dbms 可能尝试将其中一个转换为另一个。根据所涉及的类型和价值,这可能会也可能不会起作用。