【问题标题】:Returning distinct list of IDs existings in all subsets返回所有子集中存在的不同 ID 列表
【发布时间】: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


    【解决方案1】:

    您需要使用GROUP BY 而不是DISTINCT。这允许您使用聚合函数和HAVING 子句。

    SELECT
      map.eid
    FROM
      tags_to_entities    AS map
    INNER JOIN
      tag_tree            AS tree
        ON map.tid = tree.tid
    WHERE
         (tree.tid = 1 OR tree.pid = 1)
      OR (tree.tid = 2 OR tree.pid = 2)
    GROUP BY
      map.id
    HAVING
      COUNT(DISTINCT CASE WHEN (tree.tid = 1 OR tree.pid = 1) THEN 1
                          WHEN (tree.tid = 2 OR tree.pid = 2) THEN 2
                     END)
      = 2
    

    JOINWHERE 子句获取它们具有标签1 2 的所有实体。但是然后你将它们分组在一起,然后计算这些标签有多少不同的类别。只有当它是 2 时,实体才会通过HAVING 子句。

    【讨论】:

    • GROUP BY map.id 应该是 eid 还是 tid,我假设 eid
    • GROUP BY map.id 切换到GROUP BY map.eid 并按预期工作。谢谢!
    • @antennen - 是的,对不起,eid ;)
    猜你喜欢
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多