复制表1并组合table2中的值

时间:2014-06-25 00:29:52

标签: sql

我有这样的table1:

enter image description here

和table2中的其他列具有两个唯一值3和4。 如何编写查询以创建类似

的表

enter image description here

实际上我的表格比上面的表格更复杂: 我试过了:

"Select DISTINCT table1.x, table1.y ,table2.z from table1 Where table1.a = "something' 
and table1.b is Not Null, 
CROSS JOIN table2 Where table2.z='something' OR table2.z='something2' "

它不起作用...我使用的是使用sql语言的建模包,我不确定它是否与sql完全兼容。

1 个答案:

答案 0 :(得分:1)

您正在寻找两张桌子的Cartesian product。它可以简短为:

select * from table1, table2;

或明确使用cross join作为:

select table1.*, table2.*
from table1 cross join table2;

要单独过滤每个表,您可以使用子查询:

select distinct table1.x, table1.y, table2.z
from (select * from table1
  where table1.a = 'something' and table1.b is not NULL
) as table1
cross join (select * from table2
  where table2.z = 'something' or table2.z = 'something2'
) as table2;

或者使用在一个查询下组合逻辑:

select distinct table1.x, table1.y, table2.z
from table1, table2
where table1.a = 'something' and table1.b is not NULL
    and (table2.z = 'something' or table2.z = 'something2')