我有两张未发布的表格:
PEOPLE表:
ID | NAME | AGE
------------
1 | DAVE | 43
1 | ANNE | 25
1 | MIKE | 58
PLACES表:
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
答案 0 :(得分: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
答案 1 :(得分:1)
每个表中至少需要一个数据才能加入。通常,这是使用主键/外键关系处理的。您可以在PLACES表中创建一个主键(例如1 = USA,2 = GER,3 = POR,4 = JPN),然后将外键放在PEOPLE表的一列中,该列匹配每个人的适当位置(例2 = ANNE,4 = DAVE,3 = MIKE)。
答案 2 :(得分:1)
我完全不推荐这个!!!但我发现这是一个很好的挑战。我强烈建议按照肖恩的建议去做,用键做。
无论如何,此查询将在不更改您的架构的情况下为您提供您所要求的内容(它还假设您的数据已准确表示)。
示例: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
答案 3 :(得分: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;