Well, it’s a very simple question, so I hope you could help me.
I’ve two tables with this structure:
-- -----------------------------------------------------
-- 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;
This query returns all the features of the product 5:
select descripcion from features where id_product = 5;
which are:
expensive
strong
tall
Ok, now I want to get all the names of the table ‘products’ that have only all these features.
I tried something like this:
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);
But it also gives me back the products which have less or more features than the three that I’m looking for…
I hope I was clear.
Thanks in advance.
I think what you’re looking for are those products that have all three of those features that don’t have any others. If so, something like this should work:
And here is a condensed Fiddle to demonstrate.