简体   繁体   中英

Normalize contacts in MySQL database

I am trying to create a chat application with a login. I am using MySQL database for storing the user data. My table is called userData . It contains:

userID*
userPass
firstname
surname
role
contacts

OK, so this system is for staff and students and users are able to add contacts to their list. I am struggling to structure my database to store the contacts efficiently. Basically I am not sure how to normalize with the contacts column.

For example...

userID* userPass firstname surname role contacts 1234 2012 Sponge Bob Student 1345 1234 2012 Sponge Bob Student 3421 1234 2012 Sponge Bob Student 1445

Would it be appropriate for me to create a table for each userID to store the contacts? I am making this in JAVA using a MySQL db. Would be grateful for any tips.

You should have two tables, one with user data and other with contacts. This can then be joined by using the shared identifier.

CREATE TABLE userData (userID int primary key, userPass varchar(32), firstname varchar(32), surname varchar(32), roleID int);
CREATE TABLE roles (roleID int primary key, rolename char(32));
CREATE TABLE contacts (userID int, contactID int);

I threw 'roles' in there as an example. You can then join these as necessary, eg:

SELECT contacts.* FROM contacts 
JOIN userData USING (userID)
WHERE userData.userID=1234;

Or to take if further and benefit from the normalization:

SELECT CONCAT(ud.firstName,' ',ud.surName),
       CONCAT(cd.firstName,' ',cd.surName)
 FROM contacts
 JOIN userData AS cd on (cd.userID=contacts.contactID)
 JOIN userData AS ud on (ud.userID=contacts.userID)
 WHERE
  contacts.userID=1234;

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