I have a database that contains products, beds to be specific. The details of each bed is stored in a products table, but then I have a separate table, product_bedding_sizes that holds records for each size a bed can in. So one bed may have five entries in this table (it’s a one-to-many relationship).
That bit is done. However, on the public website, visitors can search products and restrict their search to a particular bed size. So my question is, how can I take an array of sizes and select all bed products that may have one or more entries for the specified sizes?
A simplified schema:
CREATE TABLE `products` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB;
CREATE TABLE `product_bedding_sizes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) unsigned NOT NULL,
`size` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `product_id` (`product_id`)
) ENGINE=InnoDB;
ALTER TABLE `product_bedding_sizes`
ADD CONSTRAINT `product_bedding_sizes_ibfk_1`
FOREIGN KEY (`product_id`)
REFERENCES `products` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
If the user selects say, 90cm and 120cm, the plain English explanation of the query would be:
Select all from the
productstable where it may have asizein theproduct_bedding_sizestable that’s 90cm or 120cm.
I take your requirement to be that a row should be returned if the product has a size of 90 OR if it has a size of 120, or both. (The query would be slightly different to return rows where the product has both size of 90 AND a size of 120.)
Any of these queries return the specified result:
–or–
— or —
— or —