请检查http://sqlfiddle.com/#!18/1acd1/2
我通过UserId来获取用户的国家信息,这样我就可以根据用户的国家来获取计划。
我有特定于国家的计划,但我没有针对所有国家的计划,所以当我传递userid时,此时我没有任何关于该用户/国家的计划,没有行返回,但在这种情况下,我需要向该用户显示默认计划(带有国家id =‘1’的计划)。
如果userid='4‘不返回任何行,请参阅小提琴,因此在这种情况下,我需要向该用户显示默认计划。所有默认计划都有countryid=1
我希望你能理解我的问题:)谢谢
发布于 2018-02-09 15:24:19
这是我对它的看法。
我采取了一种不同的方法,从tblProfile开始,因为这个查询的输入实际上是一个UserId,所以我发现遵循这个过程更符合逻辑:
UserId,获取PlanId of his CountryIdCountryId不存在于lstCountry中或没有PlanId,则将用户的CountryId替换为默认的CountryId=1 (如下面的注释所述)CountryId的计划详细信息和货币表定义
CREATE TABLE lstCountry(
CountryID int,
CountryTitle varchar(100),
CurrencyCode varchar(3))
INSERT INTO lstCountry (CountryId, CountryTitle, CurrencyCode) VALUES
(1, 'USA', 'USD'),
(2, 'GB', 'GBP'),
(3, 'France', 'EUR')
CREATE TABLE tblProfile(
UserId int,
CountryId int)
INSERT INTO tblProfile (UserId, CountryId) VALUES
(1, 1),
(2, 2),
(3, 3),
(4, 4)
CREATE TABLE tblPlan (
PlanId int,
PlanTitle nvarchar(50),
PlanPrice money,
CountryId int)
INSERT INTO tblPlan (PlanId, PlanTitle, PlanPrice, CountryId) VALUES
(1, 'PlanDefault', 10, 1),
(2, 'Plan2', 20, 2),
(3, 'Plan3', 30, 3),
(4, 'PlanDefault', 40, 1),
(5, 'Plan5', 50, 2)查询
select distinct f.PlanId,
f.PlanTitle,
f.PlanPrice,
e.CurrencyCode
from (
select case when c.PlanId is null then '1' else a.CountryId end as CountryId
from tblProfile a
left join lstCountry b on a.CountryId=b.CountryId
left join tblPlan c on b.CountryId=c.CountryId
where UserId=4
) d
inner join lstCountry e on d.CountryId=e.CountryId
inner join tblPlan f on d.CountryId=f.CountryIdUserId=1结果
| PlanId | PlanTitle | PlanPrice | CurrencyCode |
|--------|-------------|-----------|--------------|
| 1 | PlanDefault | 10 | USD |
| 4 | PlanDefault | 40 | USD |UserId=2结果
| PlanId | PlanTitle | PlanPrice | CurrencyCode |
|--------|-----------|-----------|--------------|
| 2 | Plan2 | 20 | GBP |
| 5 | Plan5 | 50 | GBP |UserId=3结果
| PlanId | PlanTitle | PlanPrice | CurrencyCode |
|--------|-----------|-----------|--------------|
| 3 | Plan3 | 30 | EUR |UserId=4结果
| PlanId | PlanTitle | PlanPrice | CurrencyCode |
|--------|-------------|-----------|--------------|
| 1 | PlanDefault | 10 | USD |
| 4 | PlanDefault | 40 | USD |以下是SQL http://sqlfiddle.com/#!18/7068c/8/0
发布于 2018-02-09 14:45:09
我认为LEFT JOIN和表的第二个解析可以实现这一点。如果没有,请查看@JuanCarlosOropeza评论,并使用示例和预期数据更新您的帖子。
SELECT p.PlanId,
p.PlanTitle,
p.PlanPrice,
ISNULL(c.CurrencyCode, d.CurrencyCode) AS CurrencyCode
FROM tblPlan p
LEFT JOIN lstCountry c ON c.CountryId = p.CountryId
LEFT JOIN lstCountry d ON c.CountryId IS NULL
AND d.CountryId = 226
WHERE P.CountryId = (SELECT sq.CountryId
FROM tblProfile sq --Not sure if this requires a Default Country
WHERE UserId = @UserId)
AND p.IsVisible = '1';https://stackoverflow.com/questions/48708096
复制相似问题