简体   繁体   中英

What type of join do I need?

For a registration page where the user enters their contact information and their username and password. I have two tables, one for a username and password with a foreignkey called contactinfo and a table of contact information that i want to join with the users table? Should both foreign and primary key also be set to auto increment?

Thanks

Set both primary keys to be auto increment. Add foreign key from user table to contact info table and your done. Foreign keys are never auto increment, after all they are meant to refer to a value in another table.

Note that if you are using an ORM like Doctrine the relationships between user and contactinformation will be handled automatically for you. Otherwise, you should insert your contact information first, get its generated primary key (via mysql_insert_id for example), then perform your insert into the user table.

user's table should have:

  • userid (primary, autoincrement)
  • username
  • password

the other table has:

  • infoid (primary, autoincrement)
  • userid (this will link this row to the other table)
  • and your data...

you should use a "left join"

The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2). (w3schools)

so we have a users table as our "left table" and info as "right table". user may not have info set just yet, but he/she has an account. so we have an account ("left") but not necessarily info ("right") - the LEFT JOIN sounds like the join for the job

and your sql should roughly look like

SELECT "columns" FROM table1
LEFT JOIN table2 ON table1.userid = table2.userid

//where "columns" are the columns you want to get
//from the tables in "table.column" notation like: user.username or info.mobile

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