1

我正在努力整理一个连接 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'”

希望你们能帮助我:)

4

2 回答 2

3

表中没有fk_brew_idFavorite但您必须将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;
于 2013-05-17T15:54:04.823 回答
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 *。当您进行连接时,您会重复列并导致查询速度变慢。

于 2013-05-17T15:56:57.463 回答