Один из способов сделать это - добавить TypeId в таблицу ThingToken, чтобы вы могли использовать его во внешних ключах. Вам также необходимо дополнительное уникальное ограничение для Thing, но вы можете включить его (TypeId, Id), чтобы оно также было полезно для поиска по TypeId и физически идентично некластерному индексу для just (TypeId).
EG:
use tempdb
go
drop table if exists ThingToken
drop table if exists TypeToken
drop table if exists Token
drop table if exists Thing
drop table if exists Type
--| Thing | | Type | | Token | | TypeToken | | ThingToken |
--|-------| |------| |-------| |-----------| |------------|
--| Id | | Id | | Id | | TypeId | | ThingId |
--| Type | |------| |-------| | TokenId | | TokenId |
--|-------| |-----------| |------------|
create table Type(Id int primary key)
create table Token(Id int primary key)
create table TypeToken
(
TypeId int not null references Type,
TokenId int not null references Token,
constraint pk_TypeToken
primary key (TypeId,TokenId)
)
create table Thing
(
Id int not null primary key,
TypeId int references Type,
constraint ak_Thing
unique (TypeId,Id)
)
create table ThingToken
(
ThingId int not null,
TokenId int not null,
TypeId int not null,
constraint pk_ThingToken
primary key (ThingId,TokenId),
constraint fk_ThingToken_Thing
foreign key (TypeId,ThingId) references Thing(TypeId, Id),
constraint fk_ThingToken_TypeToken
foreign key (TypeId,TokenId) references TypeToken(TypeId, TokenId)
)