String binding of SQL tables instead of id

Asked

Viewed 507 times

1

Data from user accounts

id  nome    sobrenome   pais    estado  cidade  telefone    url_perfil

Login data of users

id  email   senha   prioridade

My doubts are:

  • How can I link them to foreign key using string ?
  • It is more recommended to do this with the ID ? Why? (There may be problems when a user registers their data in a table, and their account has 2 id'different s being one for each table, making it difficult to use the foreign key ?)
  • For the use of Foreign key, it is necessary that the ENGINE of the bank be INNODB ?
  • How would the Join for these tables ?

PS: I searched for stack and other places if there was a "question" that answered my doubts, or at least gave me a light, but I did not find, and because of that I am opening this

  • http://stackoverflow.com/questions/1545253/how-to-add-a-column-and-make-it-a-foreign-key-in-single-mysql-statement

  • translation ? would be better :3

1 answer

4


For the use of Foreign key, it is necessary that the database ENGINE is INNODB ?

By using this engine the database automatically guarantees referential integrity it can be guaranteed via application but you program the rules and take all due care.

How can I link them to Foreign key using string ?

Yes you can. It works the same way just enter the column names in the foreign key.

How would Join for these tables?

It’s the same thing.

It is more recommended to do this with ID ? Why? (There may be problems when a user registers their data in a table, and their account has 2 different id’s being one for each table, making it difficult to use the foreign key ?)

In terms of performace numerical comparisons are faster than comparisons with strings (varchar). The size of the field string influence in the Indice ie the bigger the worse the performace.

When working with non-numeric keys the validation rigor of the values should be greater for example remove spaces, take care not to have problems with encodings.

An example of primary key as string can be seen between the city (FK) and state tables (acronym + PK name)

  • I tried to use the command alter table contas_dados add FOREIGN key(email_conta) references contas_login(email);

  • But the error occurred : #1005 - Não pode criar a tabela webtraining_contas.#sql-103c_27b (erro no. 150 "Foreign key constraint is incorrectly formed") (Informações…)

  • @Withering your PK in the other table is only email_conta or it is composed?

  • PK ? I put the email_conta as varchar(255) not null only when creating the table

  • 1

    @Murilogambôa has how to put in pastbin or question the creation of tables?

  • 1

    @Murilogambôa I made a test here, first I had to create an Indice to email_conta and then give an alter adding as foreign key.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.