0

嗯,这是一个非常简单的问题,所以我希望你能帮助我。

我有两个具有这种结构的表:

-- -----------------------------------------------------
-- Table `mydb`.`product`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`products` (
  `id_product` INT NOT NULL ,
  `name` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`id_product`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `mydb`.`features`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`features` (
  `id_feature` INT NOT NULL ,
  `id_product` INT NOT NULL ,
  `description` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`id_feature`) ,
  INDEX `fk_table2_table1` (`id_product` ASC) ,
  CONSTRAINT `fk_table2_table1`
    FOREIGN KEY (`id_product` )
    REFERENCES `mydb`.`products` (`id_product` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

此查询返回产品 5 的所有功能:

select descripcion from features where id_product = 5;

哪个是:

expensive
strong
tall

好的,现在我想获取只有所有这些功能的表“产品”的所有名称。我试过这样的事情:

select p.name from products p, features f
where p.id_product = f.id_product and
f.id_feature in 
(select id_feature from features 
where description in
(select description from features
where id_product = 5);

但它也给了我比我正在寻找的三个功能更少或更多的产品......

我希望我很清楚。提前致谢。

4

2 回答 2

1

我认为您正在寻找的是那些具有所有这三个功能而没有任何其他功能的产品。如果是这样,这样的事情应该可以工作:

SELECT P.Id_Product, P.Name
FROM Products P
    JOIN Features F ON P.id_product = F.id_product 
    JOIN Features F2 ON P.id_product = F2.id_product 
WHERE F.id_feature IN (SELECT id_feature FROM Features WHERE id_product = 5)
GROUP BY P.Id_Product, P.Name
HAVING COUNT(DISTINCT F2.id_Feature) = 3

这是一个浓缩的Fiddle来演示。

于 2013-02-13T01:05:25.627 回答
0

我认为您想使用 join 语句-我没有检查查询的确切语法,但您明白了:

SELECT * FROM `mydb`.`products`

加入mydbfeaturesmydbfeatures. id_product= mydbproducts.id_product

WHERE

`mydb`.`features`.`description` = 'strong' OR
`mydb`.`features`.`description` = 'tall' OR
`mydb`.`features`.`description` = 'expensive';
于 2013-02-13T00:52:08.560 回答