1

我的表结构如下,示例数据如下名称:用户

User   Region
Sam    USA    
Meyer  NA    
Ying   Japan    
Yang   Asia

我还有另一张桌子,上面有地区和国家

名称:地区

       Region Country         RegionList    
        USA     America            
        NA       NULL          USA            
        NA      Canada            
        NA      Mexico            
        Japan   Japan
        Asia     NULL         Central        
        Asia      NULL         East        
        Central  India        
        East     Dubai
        Central  Japan

你如何编写一个 SQL 服务器查询来列出他/她代表的每个用户和相应的国家?

像:

Sam   America
Meyer America
Meyer Canda
Meyer Mexico
Ying  Japan
Yang  Japan
Yang  India
Yang  Dubai
4

3 回答 3

5

如果您的 Region 表可能有无限多个级别,则可以使用Common Table Expression。请参阅使用公用表表达式的递归查询。

WITH UserRegions (username, region, country)
AS
(
    -- Anchor member definition
    SELECT u.[user] AS username, r.regionlist AS region, r.country
    FROM [User] u
    JOIN Region r
        ON u.Region = r.Region
    UNION ALL
    -- Recursive member definition
    SELECT ur.username, r.regionlist AS region, r.country
    FROM Region r
    INNER JOIN UserRegions AS ur
        ON r.Region = ur.Region
)
-- Statement that executes the CTE
SELECT username, country
FROM UserRegions
WHERE country IS NOT NULL
ORDER BY username

http://sqlfiddle.com/#!3/ca9de/8

于 2013-03-08T21:06:36.963 回答
0

您可以使用 JOIN 来获得您想要的结果

SELECT user, isNull(Country,RegionList) Country
FROM user
    JOIN region ON users.region = region.region
ORDER BY user, Country

如果您想返回所有用户,即使他们没有任何国家,那么您可以使用 LEFT OUTER JOIN

SELECT user, isNull(isNull(Country,RegionList),'No countries') Country
FROM user
    LEFT OUTER JOIN region ON users.region = region.region
ORDER BY user, Country
于 2013-03-08T20:59:07.787 回答
-1

根据您提供的显式架构和示例数据:

select
user, isnull(region.country, r2.country) as Country 
from 
user
left join 
region 
on user.region = region.region
left join
region r2
on r2.region = region.regionlist
于 2013-03-08T21:00:50.327 回答