无法获得连接表的结果

时间:2018-05-16 13:56:00

标签: sql pdo

我希望获得两个表的所有字段,一个名为" team",另一个" team_info"用FK打败第一个。我使用此查询检索结果:

$sql = $this->db->prepare("SELECT * FROM team
INNER JOIN team_info ON team.id = team_info.team_id
WHERE id = :team_id");

$sql->bindParam("team_id", $args["team_id"]);
$sql->execute();
$teams = $sql->fetchAll();
return $response->withJson($teams);

但这只会返回表team的字段,如何返回team_info的字段?

感谢。

-- -----------------------------------------------------
-- Table `mydb`.`team`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`team` (
  `id` INT NOT NULL,
  `country_id` INT NULL,
  `link` VARCHAR(255) NULL,
  `name` VARCHAR(255) NULL,
  `update_at` DATETIME NULL,
  PRIMARY KEY (`id`),
  INDEX `FK_country_team_country_id_idx` (`country_id` ASC),
  CONSTRAINT `FK_country_team_country_id`
    FOREIGN KEY (`country_id`)
    REFERENCES `mydb`.`country` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `mydb`.`team_info`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`team_info` (
  `team_id` INT NOT NULL,
  `country_id` INT NOT NULL,
  `venue_id` INT NULL,
  `shield_link` VARCHAR(255) NULL,
  `founded` VARCHAR(255) NULL,
  `address` VARCHAR(255) NULL,
  `phone` VARCHAR(255) NULL,
  `fax` VARCHAR(255) NULL,
  `email` VARCHAR(255) NULL,
  `official_site` VARCHAR(255) NULL,
  INDEX `id_idx` (`team_id` ASC),
  INDEX `id_idx1` (`country_id` ASC),
  INDEX `venue_id_idx` (`venue_id` ASC),
  CONSTRAINT `FK_team_team_info_team_id`
    FOREIGN KEY (`team_id`)
    REFERENCES `mydb`.`team` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_country_team_info_country_id`
    FOREIGN KEY (`country_id`)
    REFERENCES `mydb`.`country` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_venue_team_info_venue_id`
    FOREIGN KEY (`venue_id`)
    REFERENCES `mydb`.`venue` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

2 个答案:

答案 0 :(得分:2)

如果您执行以下操作:

SELECT * FROM team <------
INNER JOIN team_info ON team.id = team_info.team_id
...

使用此“*”,您只能引用“team”表中的所有列。当您使用的别名不再是问题时。

例如:

SELECT t.*, ti.* FROM team t
INNER JOIN team_info ti ON t.id = ti.team_id
WHERE id = :team_id

答案 1 :(得分:0)

你必须在select之后指定所有列,因为你使用两个表,所以你必须指定列名

  

而不是*你必须指定表的所有列,这样你才能从两个表中得到结果