我试图只选择三个组中的对象(1,2,3) 使用“WHERE gid IN(1,2,3)”选择我得到OR选择。我需要的是AND选择。
OBJECT_TABLE AS o
id | field1 | field2 | ...
VALUES
1, a, b
2, c, d
3, e, f
...
GROUP_XREF_TABLE AS gx
oid | gid
VALUES
1, 1
1, 2
1, 3
2, 2
3, 1
3, 2
...
SELECT DISTINCT o.id, gx.gid FROM `OBJECT_TABLE` AS o
LEFT JOIN `GROUP_XREF_TABLE` AS gx ON o.id = gx.oid
WHERE gx.gid IN (1,2,3)
这将输出所有行。我需要一个WHERE子句,它只输出对象id为1的行,因为只有那个对象在所有三个组中。
它是较大选择的一部分,所以重要的是这应该只在where语句中完成(如果需要,子选择应该没问题)。
答案 0 :(得分:3)
下面的子选择将找到那些在gx中有3行的oid:
SELECT o.id, gx.gid FROM `OBJECT_TABLE` AS o
LEFT JOIN `GROUP_XREF_TABLE` AS gx ON o.id = gx.oid
WHERE gx.oid IN (
SELECT oid FROM GROUP_XREF_TABLE as gx2
GROUP BY oid
HAVING count(*) = 3)
答案 1 :(得分:0)
试试这个
SELECT o.id, gx.gid FROM `OBJECT_TABLE` AS o
LEFT JOIN `GROUP_XREF_TABLE` AS gx ON o.id = gx.oid
WHERE gx.gid IN (1,2,3)
group by gx.gid