1

有很多类似的问题,但这有点不同。

我有一个表,其中一个外键将引用两个表。我使用以下查询进行测试。

CREATE TABLE users
(
    id int NOT NULL,
    username varchar(255) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE admins
(
    id int NOT NULL,
    username varchar(255) NOT NULL,
    PRIMARY KEY (id)
);


CREATE TABLE info
(
    id int NOT NULL,
    fullname int NOT NULL,
    user_id int,
    PRIMARY KEY (id),
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (user_id) REFERENCES admins(id)
);

在此处输入图像描述

以上查询工作正常。但是当我尝试在 mysql 工作台中绘制模型时,它会在我不想要的信息表中的新字段上创建。我希望 user_id 应该工作并将关系显示为用户和管理员表的外键。

还有一件事,我是否试图这样做不是很好的标准?还建议了正确的方法。

表名仅用于示例目的。这里没有逻辑。我正在尝试找到一个键作为多个表的外键的解决方案,并面临 mysql 工作台的问题。

4

1 回答 1

1

Try this:

  1. Save your DDL in a file.
  2. Create new model in MySQL Workbench
  3. File > Import > Reverse Engineer MySQL Create Script
  4. Browse to file created in step 1. Ensure that 'Place imported objects on diagram' is selected.
  5. Click 'Execute'

From a data modelling point of view you might be better off specifying a user as an admin by including an extra column on the users table. Hence:

CREATE TABLE users
(
    id int NOT NULL,
    username varchar(255) NOT NULL,
    isAdmin boolean not null default false,
    PRIMARY KEY (id)
);

CREATE TABLE info
(
    id int NOT NULL,
    fullname int NOT NULL,
    user_id int,
    PRIMARY KEY (id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);
于 2013-11-07T12:36:52.150 回答