5

我在这里给出了我的问题的一个非常抽象的版本,所以请多多包涵。我有一个查询,将检查特定主体是否具有某些相同类型的多个参数。例如,就巧克力而言,男孩有多项选择。但是,我想从桌子上选择与我提到的巧克力完全一样的男孩。不是更多,不是更少,不是“喜欢”或不是“IN()”。

SELECT boy_id from boys_chocolates WHERE chocolate_id ONLY IN('$string');

..where 当然 '$string' 是一个 PHP 变量,其中仅包含我想用来拉男孩的巧克力的逗号分隔值。

我知道这是无效的 MySQL 语句,但是否有任何有效的等价物?

编辑:

这是更全面的查询,它在特殊情况下获取记录,但并非总是如此。

SELECT boys.* FROM schools_boys INNER JOIN boys ON boys.boy_id=schools_boys.boy_id
INNER JOIN chocolates_boys a ON a.boy_id=boys.boy_id INNER JOIN schools
ON schools.school_id=schools_boys.school_id WHERE a.chocolate_id IN(1000,1003)
AND 
            EXISTS
            (
                    SELECT 1
                    FROM chocolates_boys b
                    WHERE a.boy_id=b.boy_id
                    GROUP BY boy_id
                    HAVING COUNT(DISTINCT chocolate_id) = '2'
                    )

                GROUP BY schools_boys.boy_id HAVING COUNT(*) = '2'

Boys Table
+--------+-------------+
| id     | boy         |
+--------+-------------+
| 10007  | Boy1        |
| 10008  | Boy2        |
| 10009  | Boy3        |
+--------+-------------+

Chocolates Boys Table
+----+---------+--------------+
| id | chocolate_id | boy_id |
+----+--------------+---------+
| 1  | 1000         | 10007   |
| 2  | 1003         | 10007   |
| 3  | 1006         | 10007   |
| 4  | 1000         | 10009   |
| 5  | 1001         | 10009   |
| 6  | 1005         | 10009   |
+----+--------------+---------+

当我单独选择 1000 拉出两个男孩(或)1000 和 1003 拉出 ID 为 10007 的男孩时,什么也没有发生。

4

1 回答 1

12

这个问题叫做Relational Division

SELECT boy_id 
FROM   boys_chocolates 
WHERE  chocolate_id IN ('$string')
GROUP  BY boy_id 
HAVING COUNT(DISTINCT chocolate_id) = ? -- <<== number of chocolates specified

例子:

SELECT boy_id 
FROM   boys_chocolates 
WHERE  chocolate_id IN (1,2,3,4)
GROUP  BY boy_id 
HAVING COUNT(DISTINCT chocolate_id) = 4

但是,如果chocolate_id对每个 都是唯一的boy_id,则DISTINCT关键字是可选的。

SELECT boy_id 
FROM   boys_chocolates 
WHERE  chocolate_id IN (1,2,3,4)
GROUP  BY boy_id 
HAVING COUNT(*) = 4

更新 1

...我想从桌子上挑选出我提到的巧克力的男孩。不多不少...

SELECT boy_id 
FROM   boys_chocolates a
WHERE  chocolate_id IN (1,2,3,4) AND
        EXISTS 
        (
            SELECT  1
            FROM    boys_chocolates b
            WHERE   a.boy_ID = b.boy_ID
            GROUP   BY boy_id
            HAVING  COUNT(DISTINCT chocolate_id) = 4
        )
GROUP  BY boy_id
HAVING COUNT(*) = 4
于 2013-05-09T12:27:48.597 回答