2013-01-04 151 views
0

學說查詢子我已經下表:一個一對多的關係

mysql> show columns from Person; 
+------------+--------------+------+-----+---------+-------+ 
| Field  | Type   | Null | Key | Default | Extra | 
+------------+--------------+------+-----+---------+-------+ 
|guid | varchar(255) | NO | PRI | NULL |  | 
+------------+--------------+------+-----+---------+-------+ 
mysql> show columns from Person_Func; 
+-----------+--------------+------+-----+---------+-------+ 
| Field  | Type   | Null | Key | Default | Extra | 
+-----------+--------------+------+-----+---------+-------+ 
| Person_id | varchar(255) | NO | PRI | NULL |  | 
| Func_id | varchar(255) | NO | PRI | NULL |  | 
+-----------+--------------+------+-----+---------+-------+ 
mysql> show columns from Func; 
+-------------+--------------+------+-----+---------+-------+ 
| Field  | Type   | Null | Key | Default | Extra | 
+-------------+--------------+------+-----+---------+-------+ 
| entry  | varchar(255) | NO |  | NULL |  | 
| description | varchar(255) | NO |  | NULL |  | 
| Guid | varchar(255) | NO | PRI | NULL |  | 
+-------------+--------------+------+-----+---------+-------+ 

Symfony的Person類包含一個一對多的關係Func鍵(一個人 - 幾個funcs中)使用連接表Person_Func。我想查詢Person,他有很多Funcs - steve(a,b,c);約翰(a,b,d); ele(b,d) - 我查詢(a,b)函數,應該返回steve和john。

現在我只是遍歷所有的人和查詢功能 - 這是非常非常緩慢。你可以幫我嗎?

UPD 我已經成功與

SELECT DISTINCT d1.guid from (select p.guid, f.entry from Person p, Person_Func jt, Func f where p.Guid = jt.person_id and jt.func_id = f.guid and f.entry in ('A', 'B')) as d1, 
(select p.guid, f.entry from Person p, Person_Func jt, Func f where p.Guid = jt.person_id and jt.func_id = f.guid and f.entry in ('A', 'B')) as d2 
where d1.guid=d2.guid and d1.entry != d2.entry 

但我認爲這是一個不是一個好主意,是嗎?

+0

任何運氣找到了這樣做的最佳做法? –

回答

1

鏈接Person和Person_Func與JOIN是做的更清潔的方式:

SELECT p.id 
FROM Person p INNER JOIN Person_Func pf ON p.id = pf.person_id 
       INNER JOIN Person_Func pf2 ON p.id = pf2.person_id 
WHERE 
    pf.func_id = 'a' 
    AND pf2.func_id = 'b' 

在這裏,你有SQLFiddle code