具有多个外键的表的SQL查询?

时间:2016-06-17 18:50:26

标签: mysql sql mysql-workbench

我知道MySQL支持在表中有多个外键。遇到此表创建导致错误的问题:CREATE TABLE IF NOT EXISTS ActivelyCore.Locations ( idLocation INTEGER NOT NULL AUTO_INCREMENT, CONSTRAINT idLocation_Uniq UNIQUE (idLocation), CONSTRAINT idLocation_Pk PRIMARY KEY (idLocation), idOrganization INTEGER NOT NULL, INDEX (idOrganization), CONSTRAINT Locations_Fk_idOrganization FOREIGN KEY (idOrganization) REFERENCES ActivelyCore.Organizations (idOrganization), idAddress INTEGER NOT NULL, INDEX (idAddress), CONSTRAINT Locations_Fk_idAddress FOREIGN KEY (idAddress) REFERENCES ActivelyCore.Address (idAddress), name VARCHAR(250) NOT NULL, telephone VARCHAR(15), email VARCHAR(200), website VARCHAR(200), hours VARCHAR(1000), tags VARCHAR(1000) );

SELECT  @id :=
        (
        SELECT  receiverid
        FROM    mytable
        WHERE   senderid = @id
        ) AS person
FROM    (
        SELECT  @id := 5
        ) vars
STRAIGHT_JOIN
        mytable
WHERE   @id IS NOT NULL

关于查询中可能出错的任何想法?

1 个答案:

答案 0 :(得分:0)

首先使用各自的主键创建引用表,然后可以创建位置表。

CREATE TABLE ActivelyCore.Organizations (
idOrganization INTEGER PRIMARY KEY
...)
CREATE TABLE ActivelyCore.Adress(
idAdress INTEGER PRIMARY KEY
...)

然后

CREATE TABLE IF NOT EXISTS ActivelyCore.Locations (
      idLocation INTEGER NOT NULL AUTO_INCREMENT,
      idAddress INTEGER NOT NULL,
      idOrganization INTEGER NOT NULL,
      name           VARCHAR(250) NOT NULL
      telephone      VARCHAR(15),
      email          VARCHAR(200),
      website        VARCHAR(200),
      hours          VARCHAR(1000),
      tags           VARCHAR(1000),
        CONSTRAINT idLocation_Pk PRIMARY KEY (idLocation),
        INDEX (idOrganization),
        CONSTRAINT Locations_Fk_idOrganization FOREIGN KEY (idOrganization)
          REFERENCES ActivelyCore.Organizations (idOrganization),
        INDEX (idAddress),
        CONSTRAINT Locations_Fk_idAddress FOREIGN KEY (idAddress)
          REFERENCES ActivelyCore.Address (idAddress)
    );