1

我对 MySQL 还很陌生,我正在努力通过表中指定的外键查询或引用主键。有人可以用相当简单的术语解释如何做到这一点,因为考虑到大多数其他人比我拥有更多的 MySQL 知识,我搜索的所有内容都有点难以理解。

让我们假设这些是表格:

CREATE TABLE IF NOT EXISTS customer(
    custID int AUTO_INCREMENT,
    custLname varchar(30),
    custAdd varchar(100),
    custSuburb varchar(30),
    custPcode varchar(4),
    custState varChar(20),
    custPhone varchar(10),
    PRIMARY KEY (custID)
)ENGINE = INNODB;

CREATE TABLE IF NOT EXISTS tour(
    DailyTourID int,
    tourDate DATE,
    tourTime TIME,
    tourName varchar(30),
    tourDriverID int,
    tourBusID varchar(2),
    PRIMARY KEY (DailyTourID, tourDate),
) ENGINE = INNODB;

CREATE TABLE IF NOT EXISTS TourCustLink(
    TourCustLinkID int AUTO_INCREMENT,
    TourID int,
    TourDate DATE,
    customerID int,
    PRIMARY KEY (TourCustLinkID),
    FOREIGN KEY (TourID, TourDate) REFERENCES tour(DailyTourID, tourDate),
    FOREIGN KEY (customerID) REFERENCES customer(custID)
) ENGINE = INNODB;

我知道这是一个非常糟糕的示例,但假设我想为每个客户显示 custLname、custAdd、custPhone 和 tourDates。我将如何做到这一点?

4

1 回答 1

1

JOIN他们:

SELECT 
  c.custLname,
  c.custAdd,
  c.custPhone,
  t.TourDate,
  t.TourName,
  ...
FROM TourCustLink   AS tl 
INNER JOIN Customer AS c  ON tl.customerId = c.custID
INNER JOIN Tour     AS t  ON tl.tourID     = t.DailyTourID 
                         AND tl.tourDate   = t.tourDate;

如果您想包含那些不匹配的行,您可能还需要使用OUTER JOINs (LEFT JOINRIGHT JOIN) 而不是。INNER JOIN

有关JOIN类型的更多信息,请参阅本文:

于 2013-04-25T09:32:23.470 回答