can a primary key be modified in mysql?

1

I have a query about mysql, I currently have two user tables where my main key is dni and in session. id and I have a form from php in which I update the data of a person .. my query is as follows:

Can I update the data of my main user key? in this case it is the user ID ...

I made this query in sql and it changes all the data, but when I want to modify the ID (the cedula) it always remains with it. I hope you can help me. Thanks

'$sql = "UPDATE usuarios u JOIN sesion s SET u.cedula='$cedula', u.nombres='$nombres', u.apellidos='$apellidos', u.telefono='$telefono', u.direccion='$direccion', s.correo='$correo', s.usuario='$usuario'  WHERE s.usuarios_cedula='$cedula' &&  u.cedula='$cedula'";'
    
asked by Lissi29 21.07.2017 в 03:35
source

1 answer

5

The short answer is IF YOU CAN.

The long answer is, your implementation can bring several problems; you should be careful with the updates that use JOIN . Also remember that the primary keys are unique; you can not repeat them.

My recommendation is to change the structure of your database a bit so you can use foreign keys .

In this way you can make an update to your "parent table" which could be usuarios and the changes would be cascaded to the "daughter tables"

Consider the creation of foreign keys:

ALTER TABLE 'sesion' ADD FOREIGN KEY ('id') REFERENCES 'usuarios' ('cedula') ON DELETE CASCADE ON UPDATE CASCADE;

Then the following query would update the users table and the session table.

UPDATE usuarios SET cedula='$cedula_nueva', nombres='$nombres', apellidos='$apellidos', telefono='$telefono', direccion='$direccion' WHERE u.cedula='$cedula_anterior';

And finally you could run the following query immediately afterwards in your PHP script:

UPDATE sesion SET correo='$correo', usuario='$usuario' WHERE usuarios_cedula='$cedula_anterior';
    
answered by 21.07.2017 в 06:10