简体   繁体   中英

Best way with relation tables

I have a question about tables and relations tables ...
Actually, I have these 3 tables

CREATE TABLE USER (
  ID int(11) NOT NULL AUTO_INCREMENT,
  NAME varchar(14) DEFAULT NULL
);

CREATE TABLE COUNTRY (
  ID int(11) NOT NULL AUTO_INCREMENT,
  COUNTRY_NAME varchar(14) DEFAULT NULL
);

CREATE TABLE USER_COUNTRY_REL (
  ID int(11) NOT NULL AUTO_INCREMENT,
  ID_USER int(11) NOT NULL,
  ID_COUNTRY int(11) NOT NULL,
);

Ok, so now, 1 user can have one or more country, so, several entries in the table USER_COUNTRY_REL for ONE user.
But, my table USER contains almost 130.000 entries ...
Even for 1 country by user, it's almost 10Mo for the USER_COUNTRY_REL table.
And I have several related tables in this style ...

My question is, is it the fastest, better way to do?

This would not be better to put directly in the USER table, COUNTRY field that contains the different ID (like this: "2, 6, ...")?

Thanks guys ;)

The way you have it is the most optimal as far as time constraints go. Sure, it takes up more space, but that's part of space-time tradeoff - If you want to be faster, you use more space; if you want to use less space, it will run slower (on average).

Also, think of the future. Right now, you're probably selecting the countries for each user, but just wait. Thanks to the magic of scope creep, your application will one day need to select all the users in a given country, at which point scanning each user's "COUNTRY" field to find matches will be incredibly slow, as opposed to just going backwards through the USER_COUNTRY_REL table like you could do now.

In general, for a 1-to-1 or 1-to-many correlation, you can link by foreign key. For a many-to-many correlation, you want to have a relation table in between the two. This scenario is a many-to-many relationship, as each user has multiple countries, and each country has multiple users.

Why not try like this: Create table country first

CREATE TABLE COUNTRY (
  CID int(11) NOT NULL AUTO_INCREMENT,
  COUNTRY_NAME varchar(14) DEFAULT NULL
);

Then the table user:

CREATE TABLE USER (
  ID int(11) NOT NULL AUTO_INCREMENT,
  NAME varchar(14) DEFAULT NULL,
  CID Foreign Key References CID inCountry
);

just Create a Foreign Key relation between them.

If you try to put this as explicit relation , there will lot of redundancy data.

This is the better approach. You can also make that Foreign Key as index . So that the databse retrieval becomes fast during search operations.

hope this helps..

Note : Not sure about the exact syntax of the foreign key

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