在没有任何连接条件的情况下逐列组合两个查询的结果

时间:2014-04-26 02:20:11

标签: mysql sql join

我在工作场所的一位朋友问我"如何在没有任何连接条件的情况下按列方式组合两个查询的结果?" 在谷歌搜索并尝试自己后,我无法找到任何解决方案。

表A

field1 field2 "abc1" "def1" "abc2" "def2"

表B

field3 field4 "ghi1" "jkl1" "ghi2" "jkl2"

查询结果应为:

field1 field2 field3 field4 "abc1" "def1" "ghi1" "jkl1" "abc2" "def2" "ghi2" "jkl2"

select "","",* from tableA union all select *,"","" from tableB 很接近,但结果是4行

所有连接都将交叉连接或不连接,因为我们没有任何字段来满足连接条件。

2 个答案:

答案 0 :(得分:0)

您可以使用变量在MySQL中执行此操作:

select a.field1, a.field2, b.field3, b.field4
from (select a.*, @rna := @rna + 1 as rn
      from tableA a cross join
           (select @rna := 0) const
     ) a join
     (select b.*, @rnb := @rnb + 1 as rn
      from tableB b cross join
           (select @rnb := 0) const
     ) b
     on a.rn = b.rn;

答案 1 :(得分:0)

我打算建议使用row_number(),但它似乎迫使你对其中一列进行排序。

或者,您可以尝试使用游标手动拼凑结果集:

declare @result table 
(
  field1 nvarchar(256),
  field2 nvarchar(256),
  field3 nvarchar(256),
  field4 nvarchar(256)
)

declare @cursor1 cursor
for select field1, field2 from TableA
for read only

declare @cursor2 cursor
for select field1, field2 from TableB
for read only

declare @f1 nvarchar(256)
declare @f2 nvarchar(256)
declare @f3 nvarchar(256)
declare @f4 nvarchar(256)

declare @fetchstatus1 int
declare @fetchstatus2 int

open @cursor1
open @cursor2

fetch next from @cursor1 into @f1, @f2
set @fetchstatus1 = @@FETCH_STATUS
fetch next from @cursor2 into @f3, @f4
set @fetchstatus2 = @@FETCH_STATUS
while @fetchstatus1 = 0 && @fetchstatus2 = 0
begin
  insert into @result values(@f1, @f2, @f3, @f4)

  fetch next from @cursor1 into @f1, @f2
  set @fetchstatus1 = @@FETCH_STATUS
  fetch next from @cursor2 into @f3, @f4
  set @fetchstatus2 = @@FETCH_STATUS
end

close @cursor1
close @cursor2
deallocate @cursor1
deallocate @cursor2

select field1, field2, field3, field4
from @result

你可能会感觉到我的程序编程背景虽然有点但是P