Я думаю, что вид здесь более уместен, как сказал Джейми Ид .В следующем примере вы можете создать LocalisedMessages
и LocalisedArticles
из второго запроса как представления.
-- i18n.sql (TransactSQL)
create table #Languages(ID int, Code char(2), LanguageName varchar(32));
create table #_Messages(ID int, DefaultText nvarchar(1024));
create table #Translations(ID int, MessageID int, LanguageID int, TranslatedText nvarchar(1024));
create table #Articles(ID int, TitleID int, ContentID int);
insert into #Languages(ID, Code, LanguageName) values
( 1, 'en', 'English' ),
( 2, 'es', 'Espagnol' );
insert into #_Messages(ID, DefaultText) values
( 1, 'Title 1' ),
( 2, 'Content 1' ),
( 3, 'Title 2' ),
( 4, 'Content 2' );
insert into #Translations
( ID, MessageID, LanguageID, TranslatedText ) values
( 1, 1, 1, 'Title 1' ),
( 2, 2, 1, 'Content 1' ),
( 3, 1, 2, 'Título 1' ),
( 4, 2, 2, 'Contenido 1' ),
( 5, 3, 1, 'Title 2' ),
( 6, 4, 1, 'Content 2' ),
( 7, 3, 2, 'Título 2' ),
( 8, 4, 2, 'Contenido 2' );
insert into #Articles(ID, TitleID, ContentID) values
( 1, 1, 2 ),
( 2, 3, 4 );
select _m.ID, _m.DefaultText, _t.TranslatedText, _l.ID as LanguageID, _l.Code as LanguageCode
from #_Messages _m
inner join #Translations _t on _t.MessageID = _m.ID
inner join #Languages _l on _l.ID = _t.LanguageID;
with LocalisedMessages as (
select _m.ID, _m.DefaultText, _t.TranslatedText, _l.ID as LanguageID, _l.Code as LanguageCode
from #_Messages _m
inner join #Translations _t on _t.MessageID = _m.ID
inner join #Languages _l on _l.ID = _t.LanguageID
),
LocalisedArticles as (
select _a.ID, _l.Code as LanguageCode
, isnull(_mt.TranslatedText, _mt.DefaultText) as Title
, isnull(_mc.TranslatedText, _mc.DefaultText) as Content
from #Articles _a
inner join LocalisedMessages _mt on _mt.ID = _a.TitleID
inner join LocalisedMessages _mc on _mc.ID = _a.ContentID
inner join #Languages _l on _l.ID = _mt.LanguageID and _l.ID = _mc.LanguageID
)
select *
from LocalisedArticles;
drop table #Articles;
drop table #Translations;
drop table #_Messages;
drop table #Languages;