从外键查询主键

时间:2013-04-25 09:30:05

标签: mysql sql

我对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。我该如何做到这一点?

1 个答案:

答案 0 :(得分: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 JOIN s(LEFT JOINRIGHT JOIN)代替INNER JOIN

有关JOIN类型的详细信息,请参阅此文: