Foreign key or null value

安稳与你 提交于 2019-12-24 02:42:52

问题


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;


来源:https://stackoverflow.com/questions/8404477/foreign-key-or-null-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!