在已加入的表上加入表

时间:2013-05-17 15:51:31

标签: mysql database join

我正在努力整理一个连接3个表的select语句。

这是数据库:

CREATE TABLE Beerstyles
(
  style_id     INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  style_name   VARCHAR(50) NOT NULL
)ENGINE=InnoDB;

CREATE TABLE Breweries
(
  brew_id   INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  booth_num VARCHAR(10) NOT NULL,
  brew_name VARCHAR(50) NOT NULL
)ENGINE=InnoDB;

CREATE TABLE Beers
(
  beer_id      INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  beer_name    VARCHAR(50) NOT NULL,
  alc_vol      DECIMAL(2,1) NOT NULL,
  fk_style_id  INT NOT NULL,
  fk_brew_id   INT NOT NULL
)ENGINE=InnoDB;

CREATE TABLE Favorites
(
  fav_id      INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  user_id     VARCHAR(55) NOT NULL,
  fk_beer_id  INT NOT NULL,
  fav_comment VARCHAR(255)
)ENGINE=InnoDB;


ALTER TABLE Beers ADD CONSTRAINT FK_BeerStyle_Style FOREIGN KEY (fk_style_id) REFERENCES    Beerstyles (style_id);
ALTER TABLE Beers ADD CONSTRAINT FK_BeerBrew_Brew FOREIGN KEY (fk_brew_id) REFERENCES Breweries (brew_id);
ALTER TABLE Favorites ADD CONSTRAINT FK_FavBeer_Beer FOREIGN KEY (fk_beer_id) REFERENCES Beers (beer_id);

这是第一部分:

SELECT * FROM Favorites JOIN Beers ON Favorites.fk_beer_id = Beers.beer_id

我需要混合使用brew_name,但是无法正确使用它。当我尝试加入Breweries(ON Favorites.fk_brew_id = Breweries.brew_id)时,我收到一条错误消息“'on clause'中的”未知列'Favorites.fk_brew_id'“

希望你们能帮帮我:)

2 个答案:

答案 0 :(得分:3)

fk_brew_id表中没有Favorite,但您必须将JOIN条件添加到Beers表,而不是Favorite表中这样:

SELECT 
  bw.brew_name,
  b.beer_name,
  f.fav_comment,
  ...
FROM Favorites       AS f
INNER JOIN Beers     AS b  ON f.fk_beer_id = b.beer_id
INNER JOIN Breweries AS bw ON b.fk_brew_id = bw.brew_id;

答案 1 :(得分:0)

SELECT * 
FROM Favorites 
JOIN Beers 
   ON Favorites.fk_beer_id = Beers.beer_id
JOIN Breweries 
   ON Beers.fk_brew_id = Breweries.brew_id

当然是现实生活中你永远不应该使用select *。当您有一个连接时,您正在重复列并导致查询速度变慢。