Mysql - 选择必须包含所有

时间:2011-11-22 11:00:23

标签: php mysql

我有一个问题。

100桶。 7种类型的球,每个桶中最多可包含7个球(每个桶中每种类型只有一个)。

我想从给定数组中提取所有具有最少球类型的bucketid(例如:1,3,6)。

MYSQL: bucketid, ballid - with (bucketid,ballid) as unique.

SELECT bucketid FROM table WHERE ballid IN (1,3,6)

但这会返回不正确的结果......

我该怎么做?

如果不可能,我应该使用更好的表结构吗?

3 个答案:

答案 0 :(得分:0)

尝试此查询 -

SELECT bucketid FROM bucket
GROUP BY bucketid
HAVING 
  COUNT(IF(ballid = 1, 1, NULL)) AND
  COUNT(IF(ballid = 3, 1, NULL)) AND
  COUNT(IF(ballid = 6, 1, NULL));

答案 1 :(得分:0)

使用此设置(或假设):

我创建了一个balls表,假设您知道需要过滤哪些球ID值,它们必须来自某个地方。而我添加的列maybeballname仅仅是给它(有一个balls表)稍微多一点意思就像一个球id是什么意思?所以我给它起了一个名字作为例子。仅作为一个例子。

-- balls should have its own table
CREATE TABLE balls (
    ballid INT
    , maybeballname VARCHAR(10)
);
-- sample buckets
CREATE TABLE buckets (
    bucketid INT
    , ballid INT
);

--populate with data
INSERT INTO balls VALUES(1,'BALL#1');
INSERT INTO balls VALUES(2,'BALL#2');
INSERT INTO balls VALUES(3,'BALL#3');
INSERT INTO balls VALUES(4,'BALL#4');
INSERT INTO balls VALUES(5,'BALL#5');
INSERT INTO balls VALUES(6,'BALL#6');
INSERT INTO balls VALUES(7,'BALL#7');
INSERT INTO balls VALUES(8,'BALL#8');
INSERT INTO balls VALUES(9,'BALL#9');
INSERT INTO buckets VALUES(1,1);--complete (1,3,6)
INSERT INTO buckets VALUES(1,3);
INSERT INTO buckets VALUES(1,6);
INSERT INTO buckets VALUES(1,2);
INSERT INTO buckets VALUES(1,4);
INSERT INTO buckets VALUES(2,5);
INSERT INTO buckets VALUES(2,2);
INSERT INTO buckets VALUES(3,1);
INSERT INTO buckets VALUES(4,1);--complete (1,3,6)
INSERT INTO buckets VALUES(4,3);
INSERT INTO buckets VALUES(4,6);
INSERT INTO buckets VALUES(5,3);

-- this should return bucket id values 1 and 4, right?
SELECT bk.bucketid
FROM buckets AS bk
INNER JOIN balls AS b ON bk.ballid = b.ballid
WHERE b.ballid
IN ( 1, 3, 6 ) 
GROUP BY bk.bucketid
HAVING COUNT( bk.bucketid ) >= 3 -- at least the number of ball ids provided
-- and bucket id 1 has ballid values 1-6

答案 2 :(得分:0)

这有点圆,因为MySQL只支持ALL on sub-queries,但您应该能够通过以下查询得到您想要的内容:

SELECT *
FROM table
WHERE bucketid = ALL (
    SELECT bucketid
    FROM table
    WHERE ballid IN (... your list of ballid's ...)
)