简体   繁体   中英

Table design for storing multiple ranges in MySQL database

I have several categories that I need to store in a database and present them to users. Each one has a minimum of three to a maximum of four ranges. Eg:

id | category_name | Range A |  Range B  |  Range C  |  Range D  
--------------------------------------------------------------------
 1 | Category1     | 0 - 200 | 200 - 450 | 450 - 750 | 750+
 2 | Category2     | 0 - 300 | 300 - 600 | 600+      |           
 3 | Category3     | 0 - 250 | 250 - 350 | 350 - 550 | 550+

When an user picks a category, he should then select a certain range that will be saved in the database.

    name    | category_id | category_range
------------------------------------------
 niceuser30 | 2           | A
 hellouser1 | 1           | B

Considering that:

  • ranges cannot have gaps between them (eg if range A goes from 100 to 200, range B must start from 200)
  • each range must start from 0
  • each range must be open ended (or half-open)

What would be the best design for a table to hold these values?

I was thinking of using something akin to this

id | category_name | range_a | range_b | range_c | range_d
-------------------------------------------------------------
1  | Category1     | 1500    | 3000    | 5000    | 5000
2  | Category2     | 500     | 1000    | 1000    | 

and then elaborate the output before serving it to the user (if two ranges are equal the code sets the last one "ad infinitum", so the first one would be "0 - 1500, 1500 - 3000, 3000 - 5000, 5000+") but it seems dirty and prone to errors.

you could use 2 table eg Ranges:

   id  | RangeName| Start |  End |  Range  | 
    --------------------------------------------------------------------
     1 | A        | 0    | 1500 | 1500     |
     2 | B        | 1500 | 3000 | 1500     |           
     3 | C        | 3000 | 4000 | 1000     | 
     ....

and RangeCategories :

  id   | CategoryID|RangeId| 
    --------------------------------------------------------------------
     1 | 1         |   1   | 
     2 | 1         |   2   |          
     3 | 2         |   3   | 
     4 | 2         |   1   | 
     .....

And of course you will also have your categories Table:

    id | CategoryName|...
   --------------------------------------------------------------------
     1 | Category1     | ...
     2 | Category2     | ...          
     3 | Category3     | ...

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