Foreign key or null value

2019-07-13 09:49发布

问题:

I have 2 tables: pages and menu

I want to have a pointer into menu table as foreign key to pages.id. The problem is that some menu rows don't have a link to page. When someone clicks in the link opens a submenu. How i do this in phpmyadmin?

The match i want is 1 to 1 or 1 to 0

Thanks

Maybe if i have a row to pages that has id=some_id with pages.body=null and all the menus that i want to have no submenu would have menu.pages_id=some_id Is this the right way to do that i want?

回答1:

Using some magic value for menu.pages_id doesn't work because that value whatever it is must exist on some row in the pages table.

The right way to do this is to make menu.pages_id accept NULL. It's legal for a column to be nullable even if it's part of a UNIQUE constraint and a FOREIGN KEY constraint.

CREATE TABLE menu (
  ...
  pages_id INT NULL,
  UNIQUE KEY (pages_id),
  FOREIGN KEY (pages_id) REFERENCES pages(pages_id)
) ENGINE=InnoDB;


标签: mysql key unique