2012-12-15 329 views
0

如何檢查多對一關係是否已經存在?mysql選擇是否存在一對多

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

我想搜索SampleTable.ob_id並選擇SampleTable.id,如果存在。 (1)
return 1;

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

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

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

搜索(2,3)
回報空的記錄(或空)

╔════╗ 
║ ID ║ 
╚════╝ 
+0

是您輸入的動態? – Dhinakar

+0

輸入是ob_id,它可以是任何ob_id(兩個或更多) – Deneb

回答

1
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 
+0

的組合,謝謝! ob_id與id關係是唯一的;性能如何(100k行或更多)? – Deneb

+0

如果表的索引是正確的,那麼你不必擔心性能。 –

+0

我有這個索引:PRIMARY KEY('id','ob_id'); ENGINE = MyISAM數據 – Deneb