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 使用连接表 Person_Func 包含与 Func 的一对多关系(一个人 - 几个 Func)。我想查询拥有多个 Funcs 的 Person - 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

但我认为这不是一个好主意,是吗?

4

1 回答 1

1

链接 Person 和 Person_FuncJOIN是一种更简洁的方法:

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 代码

于 2013-01-04T13:23:56.457 回答