我认为您应该重组您的文档表以仅包含与语言无关的数据(DocumentID、创建日期、创建的用户文档类型等),
然后有另一个包含每种语言数据的表 (DocumentVersion),其中 documentid 和 languageID 构成主键:
DocumentID | LanguageID | Title
但是,由于您的语言代码是每种语言的唯一值,我会将其设为自然主键(或者您可以使用 sys.syslanguages)。这是我将用于此问题的数据结构:
CREATE TABLE Document
( DocumentID INT IDENTITY(1, 1) NOT NULL CONSTRAINT PK_Document_DocumentID PRIMARY KEY,
DefaultTitle VARCHAR(100) NOT NULL,
CreatedDate DATETIME NOT NULL
);
CREATE TABLE dbo.[Language]
( LanguageCode CHAR(5) NOT NULL CONSTRAINT PK_Lanaguage_LanguageCode PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Alias VARCHAR(50) NOT NULL
);
CREATE TABLE dbo.DocumentVersion
( DocumentFK INT NOT NULL,
LanguageCode CHAR(5) NOT NULL,
Title VARCHAR(50) NOT NULL
CONSTRAINT PK_DocumentVersion PRIMARY KEY (DocumentFK, LanguageCode)
CONSTRAINT FK_DocumentVersion_LanguageCode FOREIGN KEY (LanguageCode) REFERENCES dbo.[Language] (LanguageCode),
CONSTRAINT FK_DocumentVersion_DocumentID FOREIGN KEY (DocumentFK) REFERENCES dbo.Document (DocumentID)
);
INSERT Document (DefaultTitle, CreatedDate)
VALUES
('Document 1', CURRENT_TIMESTAMP),
('Document 2', CURRENT_TIMESTAMP);
INSERT dbo.[Language] (LanguageCode, Name, Alias)
VALUES
('de-DE', 'Deutsch', 'German'),
('en-US', 'US English', 'English'),
('fr-FR', 'Français', 'French');
INSERT dbo.DocumentVersion (DocumentFK, LanguageCode, Title)
VALUES
(1, 'de-DE', 'My German Document 1'),
(2, 'de-DE', 'My German Document 2'),
(1, 'en-US', 'My English Document 1'),
(1, 'fr-FR', 'My French Document 1')
为了以您所说的方式获取文件,您需要一个自定义案例声明才能获得正确的订单。因此,对于上面的示例,您可以使用
DECLARE @PrimaryLanguage CHAR(5) = 'fr-FR',
@DefaultLanguage CHAR(5) = 'de-DE';
WITH RankedDocument AS
( SELECT DocumentFK,
LanguageCode,
Title,
SortOrder = CASE WHEN LanguageCode = @PrimaryLanguage THEN 1
WHEN LanguageCode = @DefaultLanguage THEN 2
-- MORE SORTING CRITERIA IF REQURED
ELSE 10
END
FROM DocumentVersion
), Docs AS
( SELECT d.DocumentID,
rd.Title,
d.CreatedDate,
rn = ROW_NUMBER() OVER(PARTITION BY d.DocumentID ORDER BY rd.SortOrder)
FROM Document d
INNER JOIN RankedDocument rd
ON d.DocumentID = rd.DocumentFK
)
SELECT DocumentID, Title, CreatedDate
FROM Docs
WHERE rn = 1;
法语文档示例
德国文件示例
编辑
要使用当前结构执行此操作,您需要向 中添加一个字段MyItemsTable
,这应该是新表的外键,为了演示,我刚刚使用了LinkField
:
DECLARE @PrimaryLanguage INT = 1,
@DefaultLanguage INT = 1;
WITH RankedItem AS
( SELECT ID,
Title,
LanguageId,
rn = ROW_NUMBER() OVER(PARTITION BY LinkField ORDER BY CASE LanguageId
WHEN @PrimaryLanguage THEN 1
WHEN @DefaultLanguage THEN 2
ELSE 10
END)
FROM MyItemsTable
)
SELECT ID, Title, LanguageID
FROM RankedItem
WHERE rn = 1;
SQL Fiddle 演示