小编典典

多对多和多对多交叉点

sql

假设我有一个数据库,其中包含人员,杂货店和您可以在商店中购买的商品,如下所示:

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;

谢谢你的时间!

使用数据编辑SQL


阅读 179

收藏
2021-05-23

共1个答案

小编典典

如果要解决该问题,我将把四个表及其链接列( 特别是外键 )连接在一起,然后对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
     )

SQLFiddle演示

2021-05-23