说我有了人,杂货店和项目,你可以在商店购买,像这样一个数据库:许多一对多和多对一的许多十字路口
Stores People Foods
----------------- ------------------ ------------------
| id | name | | id | name | | id | name |
----------------- ------------------ ------------------
| 1 | Giant | | 1 | Jon Skeet | | 1 | Tomatoes |
| 2 | Vons | | 2 | KLee1 | | 2 | Apples |
| 3 | Safeway | ------------------ | 3 | Potatoes |
----------------- ------------------
我有一个额外的该表用于跟踪商店卖的是什么:
Inventory
--------------------
| store_id| food_id|
--------------------
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
--------------------
而且我有上有
Lists
---------------------
| person_id| food_id|
---------------------
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 3 |
---------------------
购物清单另一个表我问题在于,给定一个人或他们的ID,找出他们可以去哪些商店的最佳方式是什么,以便他们能够将他们的一切都列入清单。在MySQL中有这些类型的计算模式吗?
我尝试(很丑陋和杂乱)是一样的东西:
-- Given that _pid is the person_id we want to get the list of stores for.
SELECT stores.name, store_id, num, COUNT(*) AS counter
FROM lists
INNER JOIN inventory
ON (lists.food_id=inventory.food_id)
INNER JOIN (SELECT COUNT(*) AS num
FROM lists WHERE person_id=_pid
GROUP BY person_id) AS T
INNER JOIN stores ON (stores.id=store_id)
WHERE person_id=_pid
GROUP BY store_id
HAVING counter >= num;
感谢您的时间!
感谢张贴表DDL/DML,但如果你创建了一个工作模型,将会变得更好[SQL小提琴(http://sqlfiddle.com/) – Taryn
像这样? http://sqlfiddle.com/#!2/83667/6 – KLee1
完美,谢谢! :) – Taryn