我有三张桌子:
部分:
+-------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | +-------+------------------+------+-----+---------+----------------+ +----+ | id | +----+ | 1 | | 2 | | 3 | +----+
部分_partid:
+-----------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+------------------+------+-----+---------+-------+ | part_id | int(10) unsigned | NO | PRI | NULL | | | partid_id | int(10) unsigned | NO | PRI | NULL | | +-----------+------------------+------+-----+---------+-------+ +---------+-----------+ | part_id | partid_id | +---------+-----------+ | 1 | 1 | | 1 | 2 | | 1 | 3 | | 2 | 1 | | 2 | 4 | | 2 | 5 | | 3 | 6 | | 3 | 7 | | 3 | 8 | +---------+-----------+
部分:
+-------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | key | varchar(50) | NO | MUL | NULL | | | value | varchar(50) | NO | | NULL | | +-------+------------------+------+-----+---------+----------------+ +----+-----+-------+ | id | key | value | +----+-----+-------+ | 1 | l | foo | | 2 | p | bar | | 3 | s | baz | | 4 | l | 3 | | 5 | p | 5 | | 6 | s | r | | 7 | l | rr | | 8 | l | rrr | +----+-----+-------+
基本上每个部分都由任意部分 ID 组成。例如,第 1 部分有 l = 'foo'、p = 'bar' 和 s = 'baz'。
如果我想搜索所有具有 l = 'foo' 的部分,我使用这个连接
SELECT p.id FROM parts AS p
INNER JOIN parts_partid ppi ON ppi.part_id = p.id
INNER JOIN partid pi ON ppi.partid_id = pi.id
WHERE pi.key = 'l' AND pi.value = 'foo';
这给了我第 1 部分和第 2 部分。
现在我想搜索所有具有 l = 'foo'和p = '5' 的部分(这应该只导致第 2 部分)。我怎样才能做到这一点?