假设这些表:
组:(ID,标题): {1,G1}, {2,G2}, {3,G3}, {4, G4}
类别:(ID,标题):{1, Cat1}, {2, Cat2}, {3, Cat3}, {4, Cat4}
产品:(Id、GroupId、CategoryId、名称):
{1, 1, 1, G1C1P1},
{2, 1, 2, G1C2P2},
{3, 1, 2, G1C2P3},
{4, 2, 2, G2C2P4},
{5, 2, 2, G2C2P5},
{6, 3, 1, G3C1P6},
{7, 3, 3, G3C3P7}
经销商:(ID,名称): {1, 'Dealer1'}, {2, 'Dealer2'}, {3, 'Dealer3'}
ProductDealer(Id、ProductId(英国)、DealerId、LastSale、编号):
{1, 1, 1, 5, '2012-12-10 12:34:31'},
{2, 2, 2, 120, '2012-11-10 12:34:31'},
{3, 5, 1, 75, '2012-12-02 12:34:31'}
所以我要创建一个完整的产品视图,这是我的第一次尝试:
SELECT
[PR].[Id],
[PR].[Name],
[PR].[GroupId],
[GR].[Title] AS [Group],
[PR].[CategoryId],
[CA].[Title] AS [Category]
FROM [dbo].[Product] AS [PR]
INNER JOIN [dbo].[Group] AS [GR] ON [PR].[GroupId] = [GR].[Id]
INNER JOIN [dbo].[Category] AS [CA] ON [PR].[CategoryId] = [CA].[Id]
然后我想添加ProductDealer
列来查看,所以我试试这个:
SELECT
[PR].[Id],
[PR].[Name],
[PR].[GroupId],
[GR].[Title] AS [Group],
[PR].[CategoryId],
[CA].[Title] AS [Category],
ISNULL(
(SELECT [PD].[Id] FROM [dbo].[ProductDealer] AS [PD]
WHERE [PD].[ProductId] = [PR].[Id]),
CAST(-1 AS BIGINT)
) AS [ProductDealerId],
ISNULL(
(SELECT [DE].[Id] FROM [dbo].[Dealer] AS [DE]
INNER JOIN [dbo].[ProductDealer] AS [PD] ON [DE].[Id] = [PD].[DealerId]
WHERE [PD].[ProductId] = [PR].[Id]),
CAST(-1 AS BIGINT)
) AS [DealerId],
ISNULL(
(SELECT [DE].[Name] FROM [dbo].[Dealer] AS [DE]
INNER JOIN [dbo].[ProductDealer] AS [PD] ON [DE].[Id] = [PD].[DealerId]
WHERE [PD].[ProductId] = [PR].[Id]),
CAST('HaveNotDealer' AS NVARCHAR)
) AS [Dealer],
ISNULL(
(SELECT [PD].[LastSale] FROM [dbo].[ProductDealer] AS [PD]
WHERE [PD].[ProductId] = [PR].[Id]),
CAST('0001-01-01 00:00:01' AS DATETIME2)
) AS [LastSale],
ISNULL(
(SELECT [PD].[Number] FROM [dbo].[ProductDealer] AS [PD]
WHERE [PD].[ProductId] = [PR].[Id]),
CAST(0 AS BIGINT)
) AS [SaleNumber]
FROM [dbo].[Product] AS [PR]
INNER JOIN [dbo].[Group] AS [GR] ON [PR].[GroupId] = [GR].[Id]
INNER JOIN [dbo].[Category] AS [CA] ON [PR].[CategoryId] = [CA].[Id]
正如您在我写了一个完整的选择查询中的每一列看到的那样,ProductDealer
我不知道有没有更好的方法来做到这一点?类似于将此列合并到第一个视图,您对最好实施它的建议是什么?
更新
在ProductDealer
表中,ProductId
是英国,所以每个产品可能有一个经销商或没有经销商,如果产品有经销商,我想要ProductDealer
查看列,如果没有,则获取我的默认值,例如:(-1,'HaveNotDealer')。