I need help to find the best solution to develop a script. Let's say we have 3 buckets (3 is not a fixed number, the number of buckets will be changed regulary): Bucket1, Bucket2, Bucket3.
Each of them contains some products:
Bucket1: apple, lime, tomato
Bucket2: tomato, lemon, cuccumber
Bucket3: bread, salami, coffee
I will use an input type:text
to get some products from the keyboard like this:
apple, lemon, bread, tomato, salami, coffee, lime
I need to find a way to develop the SQL database and the PHP script so it will only select the bucket containing only products from the list. It can contain fewer, but not more, and all of the bucket items can be found in the list from the "input type:text".
So this will only select Bucket1 and Bucket3
My worst struggle is developing the database schema. Can you, please, give me an idea so I can have a path to start on?
I can explode the input
value so I will have an array with all the required items, but I'm really stuck about the rest.
The scheme should be something like:
CREATE TABLE buckets (
bucket_num INTEGER NOT NULL,
product VARCHAR(30) NOT NULL,
UNIQUE KEY(bucket_num, product)
);
This would have rows like:
bucket_num product
1 apple
1 lime
1 tomato
2 tomato
2 lemon
2 cucumber
There's no limit on the number of buckets, or the number of products in a bucket.
The query to get the buckets from a list of products would be:
SELECT DISTINCT bucket_num
FROM buckets
WHERE product IN ('apple', 'lemon', 'bread', 'tomato', 'salami', 'coffee', 'lime')
AND bucket_num NOT IN (
SELECT bucket_num
FROM buckets
WHERE product NOT IN ('apple', 'lemon', 'bread', 'tomato', 'salami', 'coffee', 'lime')
)
Another way to write it is:
SELECT bucket_num,
COUNT(*) AS total_products,
SUM(product IN ('apple', 'lemon', 'bread', 'tomato', 'salami', 'coffee', 'lime')) AS matching_products
GROUP BY bucket_num
HAVING total_products = matching_products