10

我正在寻找关于如何合并两个没有任何共同点的表的 sql 答案。

So let's say you have these two tables without anything in common:

Guys                Girls
id    name          id   name
---  ------        ----  ------
1     abraham        5    sarah
2     isaak          6    rachel
3     jacob          7    rebeka
                     8    leah

and you want to merge them side-by-side like this:

Couples

id   name      id   name
---  ------    ---  ------
1    abraham   5    sarah
2    isaak     6    rachel
3    jacob     7    rebeka
               8    leah

How can this be done?

我正在寻找关于如何合并两个没有任何共同点的表的 sql 答案。

4

4 回答 4

18

您可以通过创建一个键(即行号)并加入它来完成此操作。

大多数 SQL 方言都支持该row_number()功能。这是一种使用它的方法:

select gu.id, gu.name, gi.id, gi.name
from (select g.*, row_number() over (order by id) as seqnum
      from guys g
     ) gu full outer join
     (select g.*, row_number() over (order by id) as seqnum
      from girls g
     ) gi
     on gu.seqnum = gi.seqnum;
于 2013-07-12T18:47:44.377 回答
4

只是因为我还是写了它,这是使用 CTE 的替代方案;

WITH guys2 AS ( SELECT id,name,ROW_NUMBER() OVER (ORDER BY id) rn FROM guys), 
    girls2 AS ( SELECT id,name,ROW_NUMBER() OVER (ORDER BY id) rn FROM girls)
SELECT  guys2.id guyid,   guys2.name guyname, 
       girls2.id girlid, girls2.name girlname
FROM guys2 FULL OUTER JOIN girls2 ON guys2.rn = girls2.rn
ORDER BY COALESCE(guys2.rn, girls2.rn);

一个用于测试的 SQLfiddle

于 2013-07-12T19:34:39.507 回答
2

假设,您想在示例中将男孩与女孩配对,并在记录之间建立某种有意义的关系(不是双关语)......

通常,您会使用单独的表来表示两者之间的关联(关系)。

在此处输入图像描述

这不会给你一个物理表,但它可以让你编写一个代表最终结果的 SQL 查询:

SELECT     Girls.ID AS GirlId, Girls.Name AS GirlName, Guys.ID AS GuyId, Guys.Name AS GuyName
FROM         Couples INNER JOIN
             Girls ON Couples.GirlId = Girls.ID INNER JOIN
             Guys ON Couples.GuyId = Guys.ID

然后您可以使用Select Into语法动态创建一个表

  SELECT     Girls.ID AS GirlId, Girls.Name AS GirlName, Guys.ID AS GuyId, Guys.Name AS GuyName
    INTO MyNewTable
    FROM         Couples INNER JOIN
                 Girls ON Couples.GirlId = Girls.ID INNER JOIN
                 Guys ON Couples.GuyId = Guys.ID

(但标准规范化规则会说最好将它们保存在不同的表中,而不是创建临时表,除非出于性能原因不这样做。)

于 2013-07-12T18:45:28.717 回答
0

我一直都需要这个——使用表格中的输入在 Excel 中创建模板。这从一张包含我的区域的表中提取,另一张包含一年中的季度。结果为每个季度/期间提供了一个区域名称。

SELECT b.quarter_qty, a.mkt_name FROM TBL_MKTS a, TBL_PERIODS b

于 2015-05-14T23:15:41.760 回答