为商店构建报告并尝试按制造商 ID 获取类别。做 MySQL 查询不走运(经验几乎为零,呵呵),但我有这个:
表架构
CREATE SCHEMA IF NOT EXISTS `table` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
USE `table` ;
-- -----------------------------------------------------
-- Table `table`.`category_description`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `table`.`category_description` (
`category_id` INT(11) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`category_id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `table`.`category`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `table`.`category` (
`category_id` INT(11) NOT NULL AUTO_INCREMENT ,
`image` VARCHAR(255) NULL ,
PRIMARY KEY (`category_id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `table`.`manufacturer`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `table`.`manufacturer` (
`manufacturer_id` INT(11) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) NOT NULL DEFAULT '' ,
PRIMARY KEY (`manufacturer_id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `table`.`product`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `table`.`product` (
`product_id` INT(11) NOT NULL AUTO_INCREMENT ,
`manufacturer_id` INT(11) NOT NULL ,
`name` VARCHAR(45) NULL ,
PRIMARY KEY (`product_id`) ,
INDEX `product_manufacturer` (`manufacturer_id` ASC) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `table`.`product_category`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `table`.`product_category` (
`product_id` INT(11) NOT NULL ,
`category_id` INT(11) NOT NULL ,
PRIMARY KEY (`product_id`, `category_id`) ,
INDEX `product_to_category_product_id` (`product_id` ASC) ,
INDEX `product_to_category_category_id` (`category_id` ASC) )
ENGINE = InnoDB;
-- Sorry if example data is not provided
MySQL 查询
SELECT category_description.name, category.category_id
FROM manufacturer
JOIN product ON product.manufacturer_id = manufacturer.manufacturer_id
JOIN product_to_category ON product_to_category.product_id = product.product_id
JOIN category ON category.category_id = product_to_category.category_id
JOIN category_description ON category_description.category_id = category.category_id
WHERE manufacturer.manufacturer_id = 7
查询结果有很多category_description.name
重复的行(我猜是继承自我的新手查询)
架构基于产品,而是选择制造商的想法,那么获得与其产品相关的所有类别都获得(独特)。
由于缺乏构建查询的知识,我有货
编辑:很抱歉,更正了category
表行名称(category.image
改为category.name
)