SQL - find all rows in one table that are in two other tables
I'm struggling with how to do the query for this. I have three
tables...ingredients, recipes, and stores. I'm trying to build a query
that will tell me what recipes I can make from the ingredients available
at a store. My tables are:
mysql> SELECT * FROM ingredients;
+---------+
| id |
+---------+
| apple |
| beef |
| cheese |
| chicken |
| eggs |
| flour |
| milk |
| pasta |
| sugar |
| tomato |
+---------+
10 rows in set (0.00 sec)
mysql> SELECT * FROM stores;
+----------+------------+
| name | ingredient |
+----------+------------+
| target | apple |
| target | chicken |
| target | flour |
| target | milk |
| target | sugar |
| wal-mart | beef |
| wal-mart | cheese |
| wal-mart | flour |
| wal-mart | milk |
| wal-mart | pasta |
| wal-mart | tomato |
+----------+------------+
11 rows in set (0.00 sec)
mysql> SELECT * FROM recipes;
+---------------+------------+
| name | ingredient |
+---------------+------------+
| apple pie | apple |
| apple pie | flour |
| apple pie | milk |
| apple pie | sugar |
| cheeseburger | beef |
| cheeseburger | cheese |
| cheeseburger | flour |
| cheeseburger | milk |
| fried chicken | chicken |
| fried chicken | flour |
| spaghetti | beef |
| spaghetti | pasta |
| spaghetti | tomato |
+---------------+------------+
13 rows in set (0.00 sec)
mysql>
Given the above I want to build a query where I give it the store name
(say wal-mart for this example) and it produces a list of the recipes I
can make from the ingredients available at wal-mart (cheeseburger &
spaghetti).
Here's the SQL to create these tables:
CREATE TABLE IF NOT EXISTS ingredients (
id varchar(32) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO ingredients (id) VALUES
('apple'),
('beef'),
('cheese'),
('chicken'),
('eggs'),
('flour'),
('milk'),
('pasta'),
('sugar'),
('tomato');
CREATE TABLE IF NOT EXISTS recipes (
`name` varchar(32) NOT NULL,
ingredient varchar(32) NOT NULL,
PRIMARY KEY (`name`,ingredient)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO recipes (`name`, ingredient) VALUES
('apple pie', 'apple'),
('apple pie', 'flour'),
('apple pie', 'milk'),
('apple pie', 'sugar'),
('cheeseburger', 'beef'),
('cheeseburger', 'cheese'),
('cheeseburger', 'flour'),
('cheeseburger', 'milk'),
('fried chicken', 'chicken'),
('fried chicken', 'flour'),
('spaghetti', 'beef'),
('spaghetti', 'pasta'),
('spaghetti', 'tomato');
CREATE TABLE IF NOT EXISTS stores (
`name` varchar(32) NOT NULL,
ingredient varchar(32) NOT NULL,
UNIQUE KEY NAME_INGREDIENT (`name`,ingredient)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO stores (`name`, ingredient) VALUES
('target', 'apple'),
('target', 'chicken'),
('target', 'flour'),
('target', 'milk'),
('target', 'sugar'),
('wal-mart', 'beef'),
('wal-mart', 'cheese'),
('wal-mart', 'flour'),
('wal-mart', 'milk'),
('wal-mart', 'pasta'),
('wal-mart', 'tomato');
No comments:
Post a Comment