【发布时间】:2023-03-20 13:10:01
【问题描述】:
为商店构建报告并尝试按制造商 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)
【问题讨论】:
-
提供模式很好。如果你在每张桌子上放 2-3 行,然后把整个东西扔到sqlfiddle.com 上,这样人们就可以玩了,那就更好了。仅通过目测,我认为您只是缺少
DISTINCT:SELECT DISTINCT category_description.name... -
架构在这里准备好了sqlfiddle.com/#!2/84a8b