我有以下表格:
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包含使用连接表Person_Func的Func(一个Person - 几个Funcs)的一对多关系。我想查询Person,它有很多Funcs - 史蒂夫(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'