假设我有一个数据库,其中包含人,杂货店和商店中可以购买的商品,如下所示:
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 |
----------------- ------------------
Run Code Online (Sandbox Code Playgroud)
我有一个额外的表,跟踪哪些商店出售什么:
Inventory
--------------------
| store_id| food_id|
--------------------
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
--------------------
Run Code Online (Sandbox Code Playgroud)
我还有另一张桌子上有购物清单
Lists
---------------------
| person_id| food_id|
---------------------
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 3 |
---------------------
Run Code Online (Sandbox Code Playgroud)
我的问题是,鉴于一个人或他们的身份,最好的方法是找出他们可以去哪些商店,这样他们就可以获得他们列表中的所有内容.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;
Run Code Online (Sandbox Code Playgroud)
谢谢你的时间!
编辑SQL小提琴数据
如果我要解决这个问题,我将用它们的链接列(特别是外键)连接四个表,然后在子句上使用子查询HAVING来计算每个人列表中的项目数。尝试一下这个,
SET @personID := 1;
SELECT c.name
FROM Inventory a
INNER JOIN Foods b
ON a.food_id = b.id
INNER JOIN Stores c
ON a.store_id = c.id
INNER JOIN Lists d
ON d.food_id = b.id
WHERE d.person_id = @personID
GROUP BY c.name
HAVING COUNT(DISTINCT d.food_id) =
(
SELECT COUNT(*)
FROM Lists
WHERE person_ID = @personID
)
Run Code Online (Sandbox Code Playgroud)