2

我有两个不相关的表:

人表:

   ID | NAME | AGE
    ------------
   1  | DAVE | 43
   1  | ANNE | 25
   1  | MIKE | 58

地方表:

ID | COUNTRY | TOWN
------------------
1  |   USA    | WILMINGTON
1  |   GER    | BERLIN
1  |   POR    | LISBON
1  |   JPN    | KYOTO

我想要这样的结果:

NAME | AGE | COUNTRY | TOWN
-----------------------------
ANNE |  25 | GER     | BERLIN
DAVE |  43 | JPN     | KYOTO
MIKE |  58 | POR     | LISBON
           | USA     | WILMINGTON
4

4 回答 4

4

让我试一试:

SELECT COALESCE(a.Name, '') Name,
       COALESCE(a.Age, '') Age,
       b.Country,
       b.Town
FROM
    (SELECT ROW_NUMBER() OVER (ORDER BY [Name]) AS RowNum, Name, Age
     FROM   People) a Right Join 
    (SELECT ROW_NUMBER() OVER (ORDER BY [Country]) AS RowNum, Country, Town
     FROM   Places) b ON a.RowNum = b.RowNum
于 2012-05-24T02:23:40.720 回答
1

我完全不推荐这个!!!但我发现这是一个很好的挑战。我强烈建议您按照 Sean 的建议使用钥匙。

无论如何,此查询将在不更改架构的情况下准确地为您提供您所要求的内容(它还假设您的数据被准确表示)。

示例:http ://www.sqlfiddle.com/#!3/a0486/8

Select Distinct
  case when town = 'Wilmington' Then NULL else Name end as Name, 
  case when town = 'Wilmington' Then NULL else Age end as Age,
  Country, 
  Town
FROM People, Places
Where 
     (Name = 'Anne' AND Town = 'Berlin')
  OR (Name = 'Dave' AND Town = 'Kyoto')
  OR (Name = 'Mike' AND Town = 'Lisbon')
  OR (Town = 'Wilmington')
Order By Country Asc

编辑

为了完成我的回答并提供更合适的解决方案,我建议您将 PlaceID 添加到两个表中,然后在其上添加左连接。

示例:http ://www.sqlfiddle.com/#!3/d5ee8/3

Create Table People(
  Name varchar(255),
  Age int,
  PlaceID int
)

Create Table Places(
  PlaceID int,
  Country varchar(255),
  Town varchar(255)
)

Insert Into People Values ('Dave', 43, 2)
Insert Into People Values ('Anne', 25, 1)
Insert Into People Values ('Mike', 58, 3)

Insert Into Places Values (1, 'Ger', 'Berlin')
Insert Into Places Values (2, 'Jpn', 'Kyoto')
Insert Into Places Values (3, 'Por', 'Lisbon')
Insert Into Places Values (4, 'USA', 'Wilmington')

Select 
  Name, Age, Country, Town 
FROM 
  Places
  Left Join People On Places.PlaceID = People.PlaceID
于 2012-05-24T02:19:20.993 回答
1

我猜你希望这些按字母顺序加入,但这并没有多大意义......

WITH x AS (SELECT *, rn = ROW_NUMBER() OVER (ORDER BY NAME) FROM People),
     y AS (SELECT *, rn = ROW_NUMBER() OVER (ORDER BY COUNTRY) FROM Places)
SELECT * FROM x FULL OUTER JOIN y ON x.rn = y.rn;
于 2012-05-24T02:20:59.440 回答
1

您需要在每个表中至少有一条数据来连接。通常这是通过主键/外键关系处理的。您可以在 PLACES 表中创建一个主键(例如 1=USA、2=GER、3=POR、4=JPN),然后将外键放置在 PEOPLE 表的列中,以匹配每个人的适当位置(例如,2=ANNE,4=DAVE,3=MIKE)。

于 2012-05-24T02:08:58.487 回答