我有四個MySQL表,其中前三個共享第一個表PK,第四個有一個FK到第三個表(見下面的模式)。是否需要加入1對1表格?
鑑於第四表的PK,我只需要第一個和第四個表中的數據。
有沒有必要加入第二張和第三張表?
舉例來說,就是:
SELECT t1.*,t4.*
FROM t1
INNER JOIN t2 ON t2.t1_idt1=t1.idt1
INNER JOIN t3 ON t3.t2_idt2=t2.idt2
INNER JOIN t4 ON t4.t3_idt3=t3.idt3
WHERE t4.idt4=123;
不是更好或更差:
SELECT t1.*,t4.*
FROM t1
INNER JOIN t4 ON t4.t3_idt3=t1.idt1
WHERE t4.idt4=123;
請解釋爲什麼一個比另一個更好。
SCHEMA
-- MySQL Script generated by MySQL Workbench
-- 08/29/14 12:34:46
-- Model: New Model Version: 1.0
SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @[email protected]@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`t1`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t1` (
`idt1` INT NOT NULL,
`data` VARCHAR(45) NULL,
PRIMARY KEY (`idt1`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t2`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t2` (
`t1_idt1` INT NOT NULL,
`data` VARCHAR(45) NULL,
PRIMARY KEY (`t1_idt1`),
CONSTRAINT `fk_t2_t1`
FOREIGN KEY (`t1_idt1`)
REFERENCES `mydb`.`t1` (`idt1`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t3`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t3` (
`t2_t1_idt1` INT NOT NULL,
`data` VARCHAR(45) NULL,
PRIMARY KEY (`t2_t1_idt1`),
CONSTRAINT `fk_t3_t21`
FOREIGN KEY (`t2_t1_idt1`)
REFERENCES `mydb`.`t2` (`t1_idt1`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t4`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t4` (
`t3_t2_t1_idt1` INT NOT NULL,
`data` VARCHAR(45) NULL,
INDEX `fk_t4_t31_idx` (`t3_t2_t1_idt1` ASC),
CONSTRAINT `fk_t4_t31`
FOREIGN KEY (`t3_t2_t1_idt1`)
REFERENCES `mydb`.`t3` (`t2_t1_idt1`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET [email protected]_SQL_MODE;
SET [email protected]_FOREIGN_KEY_CHECKS;
SET [email protected]_UNIQUE_CHECKS;
如果您不使用任何內容,則無需加入表格。 – Barmar 2014-08-29 19:45:52
@Barmar我問的原因是我不確定性能是否會受到索引的影響。 – user1032531 2014-08-29 19:46:33
@Barmer。請回答這個問題,然後如果你被拒絕了,我知道你可能是不對的:) – user1032531 2014-08-29 19:47:32