简体   繁体   中英

Without using enums, what's the best way to enter data from a set of preselected data for MySQL?

For example's sake, I'm going to say I'm making a database for previous presidents in a fictional world, where they have the Windows party, the Mac party, the Debian party, the Ubuntu Party, and the Unix Party. There's no other parties, but that might change every now and then (There are no 'independents'). I want to scrape the data from a website that has these listed using web scraping libraries for PHP, but I'm worried that it might screw up when they change the website at some point, and accidentally enter any other entries than the following if I use char for MySQL. So for instance, if the website makes a typo and enter Ubunta instead of Ubuntu , that would mess up my db.

So instead of sanitizing data from the PHP side, what steps can I take to make sure any other entry than the preselected list of parties would spit out an error? Here are the options I considered so far:

  • I know I can use the enum datatype, but I heard it's not really recommended. I'm using Laravel for data input, and it's supported on newer versions, but enum itself, I heard, was not really a recommended way of doing things, especially on mySQL.

  • I also know that I can use PHP side validation. But I'm looking for better ways when there are more "preselected options", such as countries; For example, I wouldn't want to have code that has something like if(country === "Afghanistan" || "United States" || ...) for something like 240 entries. I also would like to add additional parties if I could, but I would like it to be maintainable, so people don't have to search to where to add additional if conditions.

  • I also saw that I can use trigger, but I would like to keep it short, if I were to use something like countries. I also would have to update these triggers manually, since Laravel doesn't support building trigger functions and have to do DB::unprepared .

  • Creating a custom datatable for these parties or countries . Probably the best option, and would work well for longer list of options, like country , but it seems wildly unnecessary for shorter list of options, like party , where there are only 5 parties. Would having FOREIGN KEY for SELECT statements speed up the query instead of doing WHERE ?

MySQL 8.0.16 supports check constraints. That is one option.

However, if the values change over time, your best option is a reference table (your last option). A properly declared foreign key constraint does exactly what you want. And adding new values in the future is as simple as adding a new row into the reference table.

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