问:有什么方法可以在“标准 SQL”中实现自记录枚举吗?
EXAMPLE:
Column: PlayMode
Legal values: 0=Quiet, 1=League Practice, 2=League Play, 3=Open Play, 4=Cross Play
我一直所做的只是将字段定义为“char(1)”或“int”,并将助记符(“联赛练习”)定义为代码中的注释。
有更好的建议吗?
我肯定更喜欢使用标准 SQL,因此数据库类型(mySql、MSSQL、Oracle 等)无关紧要。我也更喜欢使用任何应用程序语言(C、C#、Java 等),因此编程语言也不重要。
非常感谢您!
附言: 据我了解,使用第二个表 - 将代码映射到描述,例如“表播放模式(char(1)id,varchar(10)名称)” - 非常昂贵。这一定是正确的吗?
最佳答案
通常的方法是使用静态查找表,有时称为“域表”(因为它的目的是限制列变量的域。)
将任何枚举等的基础值与数据库中的值保持同步取决于您(您可以编写一个代码生成器来从域表中生成枚举,当域中的某些内容被调用时表被更改。)
这是一个例子:
--
-- the domain table
--
create table dbo.play_mode
(
id int not null primary key clustered ,
description varchar(32) not null unique nonclustered ,
)
insert dbo.play_mode values ( 0 , "Quiet" )
insert dbo.play_mode values ( 1 , "LeaguePractice" )
insert dbo.play_mode values ( 2 , "LeaguePlay" )
insert dbo.play_mode values ( 3 , "OpenPlay" )
insert dbo.play_mode values ( 4 , "CrossPlay" )
--
-- A table referencing the domain table. The column playmode_id is constrained to
-- on of the values contained in the domain table playmode.
--
create table dbo.game
(
id int not null primary key clustered ,
team1_id int not null foreign key references dbo.team( id ) ,
team2_id int not null foreign key references dbo.team( id ) ,
playmode_id int not null foreign key references dbo.play_mode( id ) ,
)
go
有些人出于“经济”的原因可能会建议对所有此类代码使用一个包罗万象的表,但根据我的经验,这最终会导致困惑。最佳做法是为每组离散值创建一个小表。
关于sql - 在基于 SQL 的应用程序中 self 记录 "codes"的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8747982/