简体   繁体   中英

MySQL Database Design. How to use dates in a relational database?

I'm in the process of building a database compiling various news articles from various sources and I'm trying to work out the most efficient way to catalogue the dates the articles were written.

As it stands I'm thinking of having one table with all the dates on, then pointing the article entries in the DB to the appropriate entry in the date table.

Obviously several problems with that spring to mind, not least of which being the incredibly unwieldy and excessively long list of dates I would have to create.

Is there a more efficient way of doing this? Bearing in mind that several tables within my database will be using the dates table.

Thanks in advance, and thank you for reading my essay...

Use the MySQL DateTime format . Don't create a separate table for dates. MySQL is optimized for storing that format in each record and performing operations on it.

Creating a separate table for dates is more used for OLAP than OLTP , and I assume you are building an OLTP system.

The biggest problem with creating a separate table is that you would need to have a record for every possible time that might be used, and then you need to perform a lookup on that table to find the foreign key. That just is not a good idea at all.

Seeing as you are asking this question, I don't believe that you would need to get any more optimized than simply storing the datetime in each row. If you were building something where it would matter, you would probably know better than I would anyways.

As Ethan has suggested simply store the date in the same table as the article, no need for a lookup.

You may wish to store some details of an article separate from the body of the text, to potentially speed up searches but I would start simple. Store all relevant data in one table and only resort to partitioning if things are running slowly (avoid premature optimisation).

In addition to your main tables I would advise you to create an auxiliary Calendar Table to assist in date based queries. Contrary to what you said:

...the incredibly unwieldy and excessively long list of dates I would have to create.

A table containing dates for the next 50 years is only just over 18k rows, not much at all.

If you are going to be working with dates a lot I'd recommend you take a look at Developing Time-Oriented Database Applications in SQL by Richard Snodgrass, it's an excellent resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM