mysql选择是否存在一对多

时间:2012-12-15 12:40:37

标签: mysql sql one-to-many exists

如何检查多对一关系是否已经存在?

SampleTable
╔════╦═══════╗
║ ID ║ OB_ID ║
╠════╬═══════╣
║  1 ║     1 ║
║  1 ║     2 ║
║  2 ║     3 ║
║  2 ║     1 ║
║  2 ║     2 ║
║  3 ║     1 ║
║  3 ║     3 ║
╚════╩═══════╝

我想搜索SampleTable.ob_id并选择SampleTable.id(如果存在)。

搜索(1,2)
返回1;

╔════╗
║ ID ║
╠════╣
║  1 ║
╚════╝

搜索(1,2,3)
返回2;

╔════╗
║ ID ║
╠════╣
║  2 ║
╚════╝

搜索(2,3)
返回空记录集(或null)

╔════╗
║ ID ║
╚════╝

1 个答案:

答案 0 :(得分:2)

SELECT ID
FROM tableName a
WHERE ob_id IN (1,2,3)
GROUP BY ID
HAVING COUNT(*) =
            (
              SELECT COUNT(*)
              FROM TableName b
              WHERE b.ID = a.ID
            ) AND
      COUNT(*) = 3 -- the value of this depend on the number of values
                   -- you have supplied on you where clause.

如果ob_ID没有为每个ID定义唯一约束,则需要使用DISTINCT

SELECT ID
FROM tableName a
WHERE ob_id IN (1,2)
GROUP BY ID
HAVING COUNT(DISTINCT ob_id) =
            (
              SELECT COUNT(DISTINCT ob_id)
              FROM TableName b
              WHERE b.ID = a.ID
            ) AND
      COUNT(DISTINCT ob_id) = 2