我的表格结构如下,样本数据如下 姓名:用户
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
答案 0 :(得分:5)
如果您的Region表可能无限多级,您可以使用Common Table Expression。见Recursive Queries Using Common Table Expressions.
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
答案 1 :(得分: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
答案 2 :(得分:-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