具有多个ID的MySQL关系部门

时间:2018-02-01 16:15:04

标签: mysql relational-division

请查看此处描述的问题:MySQL ONLY IN() equivalent clause,关于MySQL中的关系部门。

我的数据库结构与描述的数据库结构非常相似,但在“巧克力男孩表”中,我有一个额外的ID字段 - 我们称之为牛奶ID。

巧克力男孩表

+----+---------+-----------------------+
| id | chocolate_id | milk id | boy_id |
+----+--------------+---------+--------+
| 1  | 1000         | 2000    | 10007  |
| 2  | 1003         | 2001    | 10007  |
| 3  | 1006         | 2005    | 10007  |
| 4  | 1000         | 2001    | 10009  |
| 5  | 1001         | 2000    | 10009  |
| 6  | 1005         | 2008    | 10009  |
+----+--------------+---------+--------|

目标是运行一个查询,检索包含我传入的确切巧克力和牛奶ID的男孩ID。以下是我预期结果的一些示例:

示例#1:

Chocolate IDs Passed In (in order) - 1000,1003,1006.
Milk IDs Passed In (in order) - 2000,2001,2005.
Expected Result: Query returns boy ID of 10007.

示例#2:

Chocolate IDs Passed In (in order) - 1000,1003.
Milk IDs Passed In (in order) - 2000,2001.
Expected Result: Empty result set.

示例#3:

Chocolate IDs Passed In (in order) - 1003,1000,1006.
Milk IDs Passed In (in order) - 2000,2001,2005.

预期结果:空结果集 - 传入的ID包含在男孩ID 10007中,但顺序错误。如果逐行检查,巧克力ID和牛奶ID的值不匹配。

我正在尝试使用John Woo解决方案的略微修改版本,以便合并添加的ID字段:

SELECT boy_id 
FROM   boys_chocolates a
WHERE  chocolate_id IN (1003,1000,1006) AND milk_id IN (2000,2001,2005) AND
    EXISTS 
    (
        SELECT  1
        FROM    boys_chocolates b
        WHERE   a.boy_ID = b.boy_ID
        GROUP   BY boy_id
        HAVING  COUNT(DISTINCT chocolate_id) = 3
    )
GROUP  BY boy_id
HAVING COUNT(*) = 3

我遇到的问题是IN函数不强制执行顺序,如示例#3所示。我想上面的查询返回一个空结果集。需要改变什么才能解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试这种方法:

SELECT a.boy_id
FROM
  (SELECT id, boy_id FROM boys_chocolates WHERE chocolate_id = 1000) a
JOIN
(
  (SELECT id, boy_id FROM boys_chocolates WHERE chocolate_id = 1003) b,
  (SELECT id, boy_id FROM boys_chocolates WHERE chocolate_id = 1006) c,
  (SELECT id, boy_id FROM boys_chocolates WHERE milk_id = 2000) d,
  (SELECT id, boy_id FROM boys_chocolates WHERE milk_id = 2001) e,
  (SELECT id, boy_id FROM boys_chocolates WHERE milk_id = 2005) f
)
ON a.boy_id = b.boy_id AND a.boy_id = c.boy_id AND a.boy_id = d.boy_id 
  AND a.boy_id = e.boy_id AND a.boy_id = f.boy_id AND b.id > a.id 
  AND c.id > b.id AND e.id > d.id AND f.id > e.id;

1000 1003 1006替换为您的第一个chocolate_id,第二个chocolate_id,第三个chocolate_id。同时将2000 2001 2005替换为您的第一个milk_id,第二个milk_id,第三个milk_id。