Reputation: 15
I have one column in my table that can store one value or two value at one record.
For example I have a table for users that they can store one or two address. Notice, they can't store more than two address, it's limit.
I have 2 way in my mind:
1- Set two column in my table for two value.
2- Create another table for 2nd value.
I need help to find best way.
Upvotes: 1
Views: 192
Reputation: 36649
1- Set two column in my table for two value. 2- Create another table for 2nd value.
It depends on your actual data. First of all, you should get a basic understanding of database design principles and normalization. Normalization is primarily to save space and help ensuring data consistency.
For your concrete issue: You say that you have two values
and that one record can either store one or two of them.
Lets assume the value is a primitive type like INT
. In this case, I would go with one table having two columns:
CREATE TABLE dataTable (
first INT NOT NULL,
second INT
);
This table can store one number (first
) and an optional second
number. I omitted a primary key which, in reality, you should add.
Now, you say that you want to store addresses
. An address
is not a primitive type, since it is usually composed of first name, last name, street, zip code, city, and depending on your location some additional information.
Again, the straight forward way would be to simply create one table with two sets of these data:
CREATE TABLE dataTable (
firstName VARCHAR(40),
lastName VARCHAR(40),
street VARCHAR(40),
zipCode INT,
firstName2 VARCHAR(40),
lastName2 VARCHAR(40),
street2 VARCHAR(40),
zipCode2 INT
);
However, this approach is unflexible and might also waste space. In this case, I would separate ("normalize") the schema and use two tables:
CREATE TABLE address (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
firstName VARCHAR(40),
lastName VARCHAR(40),
street VARCHAR(40),
zipCode INT
);
CREATE TABLE dataTable (
first INT NOT NULL,
second INT,
FOREIGN KEY (first) REFERENCES address(id),
FOREIGN KEY (second) REFERENCES address(id)
);
With this approach, you can store ("reference") either one or two addresses in your data table. The drawback is, of course, that you need to insert data into two tables when creating a new record, and that you need to properly join the tables in your queries. However, it allows you for example to add additional constraints, e.g. to define that a first name is optional, but a last name is mandatory ("NOT NULL"). This would not be possible with the first approach, since you could not distinguish between the whole (second) address being optional or only the first name being optional.
notice they can't store more than two address,It's limit.
Well - yes, until your customer comes back and needs to store three :-)
Upvotes: 1