Search code examples
mysqlsqlheidisql

composite primary key as foreign key deleting one set delets all


I have two tables one of them has composite primary key and the other has foreign keys to it. They both are set to cascade on delete. The problem is when I delete lets say a composite key set "name: John date: 02.02.2018" from the main table all the John rows are deleted from the table with the foreign keys, but there can be a set "name: John date: 04.04.2018" and also all rows where date is 02.02.2018 are also deleted how can I make it delete rows where only the set of foreign key is matched?

Update:

CREATE TABLE messages (
    session_date date NOT NULL,
    chat int(11) NOT NULL,
    message longtext NOT NULL,
    date time NOT NULL,
    receiver int(11) NOT NULL,
    PRIMARY KEY (date,receiver),
    KEY FK_messages_sessions (session_date,chat),
    KEY FK_messages_sessions_2 (chat,session_date),
    CONSTRAINT FK_messages_sessions 
        FOREIGN KEY (session_date) 
        REFERENCES sessions (session_date) 
        ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT FK_messages_sessions_2 
       FOREIGN KEY (chat) 
       REFERENCES sessions (chat) 
       ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Solution

  • You have defined two foreign keys instead of a composite foreign key.

    Try:

    CREATE TABLE `messages` (
      `session_date` date NOT NULL,
      `chat` int(11) NOT NULL,
      `message` longtext NOT NULL,
      `date` time NOT NULL,
      `receiver` int(11) NOT NULL,
      PRIMARY KEY (`date`,`receiver`),
      KEY `FK_messages_sessions` (`session_date`,`chat`),
      CONSTRAINT `FK_messages_sessions` 
          FOREIGN KEY (`session_date`, `chat`) 
          REFERENCES `sessions` (`session_date`, `chat`) 
          ON DELETE CASCADE ON UPDATE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    

    (session_date,chat) could also be (chat,session_date) depending on the order of these columns in the primary key defined in the referenced table.