【发布时间】:2012-04-08 06:16:34
【问题描述】:
我有两张桌子
Table "public.tags_to_entities"
Column | Type | Modifiers
--------+---------+-----------
tid | integer | not null
eid | integer | not null
Table "public.tag_tree"
Column | Type | Modifiers
--------+---------+-----------
tid | integer | not null
pid | integer | not null
level | integer |
tag_tree 包含标签之间的所有关系,这意味着SELECT pid FROM tag_tree WHERE tid = ? 将返回该标签的父母。 level 列在那里或只有ORDER BY。
我想返回所有eid 的列表,这些eid 在每个标签子集中至少有一个标签。使用以下查询执行一个子集
SELECT DISTINCT eid
FROM tags_to_entities
WHERE
tags_to_entities.tid = 1 OR
tags_to_entities.tid IN (SELECT tag_tree.tid FROM tag_tree WHERE tag_tree.pid = 1));
这将返回标签 1 或其子标签之一中存在的所有 eid。如果我想返回至少存在于与1 和 2 相关的标签之一中的所有eid。到目前为止,我失败的方法是
SELECT DISTINCT eid
FROM tags_to_entities
WHERE
(
tags_to_entities.tid = 1 OR
tags_to_entities.tid IN (SELECT tag_tree.tid FROM tag_tree WHERE tag_tree.pid = 1)) AND
(
tags_to_entities.tid = 2 OR
tags_to_entities.tid IN (SELECT tag_tree.tid FROM tag_tree WHERE tag_tree.pid = 2));
这不起作用,因为 tid 不能同时是 1 和 2。我该如何解决这个问题? (eid稍后会与entrys表连接)
【问题讨论】:
标签: sql postgresql-9.0