0

My question is

What is correct to make a relationship 1-1 in MySQL?

The data in the child table must be unique Exists confusing information on the internet about doing this. In my opinion the first form is correct because it is easier.

DROP TABLE IF EXISTS test.users;
CREATE TABLE test.users(

    idUser CHAR( 5 ) BINARY NOT NULL,
    name VARCHAR( 40 ) NOT NULL,
    lastName VARCHAR( 25 ) NOT NULL,
    maternalSurname VARCHAR( 25 ) NOT NULL,

    PRIMARY KEY( idUser )

)
ENGINE = InnoDB;

--

DROP TABLE IF EXISTS test.activities;
CREATE TABLE test.activities(

    user CHAR( 5 ) BINARY NOT NULL,
    sessionActive BOOLEAN NOT NULL DEFAULT FALSE,
    live DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
    attempt TINYINT UNSIGNED NOT NULL DEFAULT 0,

    PRIMARY KEY( user ),

    FOREIGN KEY( user ) REFERENCES users( idUser )
    ON DELETE CASCADE ON UPDATE CASCADE

)
ENGINE = InnoDB;

Another way I found to do

DROP TABLE IF EXISTS test.users;
CREATE TABLE test.users(

    idUser CHAR( 5 ) BINARY NOT NULL,
    name VARCHAR( 40 ) NOT NULL,
    lastName VARCHAR( 25 ) NOT NULL,
    maternalSurname VARCHAR( 25 ) NOT NULL,

    PRIMARY KEY( idUser )

)
ENGINE = InnoDB;

--

DROP TABLE IF EXISTS test.activities;
CREATE TABLE test.activities(

    idActivity INT UNSIGNED NOT NULL,
    sessionActive BOOLEAN NOT NULL DEFAULT FALSE,
    live DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
    attempt TINYINT UNSIGNED NOT NULL DEFAULT 0,
    user CHAR( 5 ) BINARY NOT NULL,

    UNIQUE( user ),

    PRIMARY KEY( idActivity ),

    INDEX( user ),
    FOREIGN KEY( user ) REFERENCES users( idUser )
    ON DELETE CASCADE ON UPDATE CASCADE

)
ENGINE = InnoDB;

what is the correct

Greetings from México!!!!

Walter Mitty
  • 18,205
  • 2
  • 28
  • 58
  • 1-m and 1-1 could be coded exactly the same. What you have here are different ways to choose index and PK, and this is not an issue specific to 1-1 relationship. Note that if you choose a PK of the child other than the PK of the parent, you need to determine how to make that key unique. – NoChance Dec 03 '14 at 20:37
  • Normally for 1-1 relationships you create a column in one table that references the primary key of another. There's no need for an intermediate table except for M-M relationships. I think you're doing it mostly right here, but having `CHAR(5) BINARY` as your primary key is more than a little annoying. Why not just a standard-issue `INT AUTO_INCREMENT`? – tadman Dec 03 '14 at 21:04

0 Answers0