如何"项目" 2桌

时间:2014-09-15 13:07:43

标签: sql

拥有以下表格:

  • " TypeSomething(ID,NAME) - 2个条目 - Id 1和2"
  • " OtherThings(ID,NAME) - 3个条目 - Id 10,20,30"

检索以下SQL结果的最简单方法是什么:

TypeId,OtherThingId:(1,10)(1,20)(1,30)(2,10)(2,20)(2,30)

...谢谢

4 个答案:

答案 0 :(得分:2)

这是笛卡儿式加入

select t.id TypeId,
       o.id OtherThingId
  from TypeSomething t 
         cross join OtherThings o

我添加了 SQL 92标准不需要的cross join,以便强调查询不是典型错误时< em> join刚刚离开。

答案 1 :(得分:1)

看起来你只想要一个交叉连接(也称为笛卡尔积):

SELECT 
    t.ID TypeId, 
    o.ID OtherThingId
FROM TypeSomething, OtherThings 

答案 2 :(得分:0)

只需使用没有谓词的join

select t.id TypeId
,      o.id OtherThingId
from   TypeSomething t
join   OtherThings o
on     1=1

答案 3 :(得分:0)

您想要的是cartesian product,可以隐式编写为:

SELECT TypeSomething.Id AS TypeId, OtherThings.Id AS OtherThingId 
FROM TypeSomething, OtherThings 
ORDER BY TypeSomething.Id, OtherThings.Id

或明确表示为CROSS JOIN

SELECT TypeSomething.Id AS TypeId, OtherThings.Id AS OtherThingId
FROM  TypeSomething
CROSS JOIN OtherThings 
ORDER BY TypeSomething.Id, OtherThings.Id