Ver Mensaje Individual
  #3 (permalink)  
Antiguo 17/12/2007, 07:56
Avatar de gnzsoloyo
gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 5 meses
Puntos: 2658
Re: Relacionar dos tablas en mysql

Bueno, el ejemplo usando DROP FOREIGN KEY es para eliminar la relación establecida entre dos tablas relacioadas, no para crearla.

Para crearla desde el inicio, suponiendo dos tablas:
Cita:
CREATE TABLE `sesiones` (
`IDSESION` int(11) NOT NULL auto_increment,
`INICIO` datetime NOT NULL,
`FINAL` datetime default NULL,
`USERNOMBRE` char(50) NOT NULL,
`IPORIGEN` char(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `usuariosbase` (
`USERNOMBRE` char(50) NOT NULL,
`NOMBRE` char(50) NOT NULL,
`PWDUSER` varchar(32) NOT NULL,
`IPORIGEN` char(20) NOT NULL,
`IDGRUPO` int(10) unsigned NOT NULL,
`INICIADO` tinyint(1) unsigned NOT NULL,
`ESTADO` char(1) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Estas dos tablas tienen que relacionarse a través de USERNOMBRE, de modo que de una de ellas se deberá referirse a la otra: SESIONES.USERNOMBRE -> USUARIOSBASE.USERNOMBRE

Cita:
CREATE TABLE `sesiones` (
`IDSESION` int(11) NOT NULL auto_increment,
`INICIO` datetime NOT NULL,
`FINAL` datetime default NULL,
`USERNOMBRE` char(50) NOT NULL,
`IPORIGEN` char(15) NOT NULL,
PRIMARY KEY (`IDSESION`),
KEY `FK_sesiones_USERS` (`USERNOMBRE`),
CONSTRAINT `FK_sesiones_USERS` FOREIGN KEY (`USERNOMBRE`) REFERENCES `usuariosbase` (`USERNOMBRE`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
y la segunda DEBE tener por clave el campo referido:

Cita:
CREATE TABLE .`usuariosbase` (
`USERNOMBRE` char(50) NOT NULL,
`NOMBRE` char(50) NOT NULL,
`PWDUSER` varchar(32) NOT NULL,
`IPORIGEN` char(20) NOT NULL,
`IDGRUPO` int(10) unsigned NOT NULL,
`INICIADO` tinyint(1) unsigned NOT NULL,
`ESTADO` char(1) NOT NULL default 'A',
`BARCOLOR` smallint(5) unsigned NOT NULL default '3',
`BARFONT` smallint(5) unsigned NOT NULL default '1',
`FONBARCOLOR` smallint(5) unsigned NOT NULL default '0',
`PANTCOLOR` smallint(5) unsigned NOT NULL default '3',
PRIMARY KEY (`USERNOMBRE`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Hay que notar que en el primer caso también hay una clave primaria.