Joh*_*ith 7 sql schema database-design
我想在关系数据库(MySQL,PostgreSQL等)中存储部分日期.例如,输入可能只是年份(2013年); 年和月(2013-08); 或年,月,日(2013-08-29).我不能只使用正常的DATE类型,因为年份将扩展到2013-01-01,这与年,月和日无法区分.
我想到要么将日期分成三个单独的字段(年,月,日作为整数),但我在DBS中丢失所有日期细节并且必须管理更多的指标.
我的另一个想法是将它存储为DATE,并有另一个专栏说明日期是多么精确.例如,"2013-08-01"和"月份"表示日期仅精确到月份(2013-08).'2013-08-01'和'day'表示日期完全是2013-08-01.
最好的方法是什么?
我认为有两种可能的方法:
(1)存储日期的子字符串,例如:
'2013' -- year 2013
'2013-01' -- year 2013, January
'2013-01-01' -- year 2013, January 1
Run Code Online (Sandbox Code Playgroud)
(2)存储3个不同的列,年,月,日(并且您可以毫无问题地建立索引年+月+日)
2013 null null -- year 2013
2013 1 null -- year 2013, January
2013 1 1 -- year 2013, January 1st
Run Code Online (Sandbox Code Playgroud)
哪一种最好取决于您想要如何查询数据。假设您有存储过程并且想要传递一个参数以使所有行都符合条件。
在情况(1)中,您传递字符串@Date = '2013-01'作为参数,并且希望获取年份 = 2013 和月份 = 01 的所有行。因此该where子句如下所示:
where left(Date, len(@Date)) = @Date
Run Code Online (Sandbox Code Playgroud)
在情况(2)中,您传递三个参数 -@Year = 2013, @Month = 1, @Day = null该where子句将类似于:
where
Year = @Year and -- Supposing @Year is always not null
(@Month is null or @Month is not null and Month = @Month) and
(@Day is null or @Day is not null and Day = @Day)
Run Code Online (Sandbox Code Playgroud)
它可能会更复杂,具体取决于您想要如何处理行。例如,如果您给出类似 的参数2013-01,您是否想要获取 Month = null 的行?
另一方面,如果您想传递日期并检查它是否属于日期范围,那么 Gordon Linoff 建议是一个不错的选择。