比较同一个表中两行之间的一个字段

时间:2015-02-12 21:18:57

标签: sql postgresql self-join

我有一个小表,其中包含我正在努力寻找查询的组成员资格。

   uid     groupid     userid
    1         2          5
    2         2          6
    3         1          2
    4         3          8
    5         4          7

我想知道如果两个给定的用户ID位于同一组中,是否可以返回TRUE?

3 个答案:

答案 0 :(得分:2)

SELECT groupid, CASE WHEN COUNT(distinct userid) > 1 THEN "TRUE" ELSE "FALSE" END
FROM my_table
WHERE userid IN ('x', 'y')
GROUP BY groupid

请注意,x和y应替换为给定的用户ID

<强> TRUE:

SELECT groupid, CASE WHEN COUNT(distinct userid) > 1 THEN 'TRUE' ELSE 'FALSE' END
FROM my_table
WHERE userid IN (5,6)
GROUP BY groupid

<强> FALSE:

SELECT groupid, CASE WHEN COUNT(distinct userid) > 1 THEN 'TRUE' ELSE 'FALSE' END
FROM my_table
WHERE userid IN (5,2)
GROUP BY groupid

http://sqlfiddle.com/#!15/3f156/1

答案 1 :(得分:2)

以下内容将获得具有两个给定成员的所有组:

select groupid
from table t
where userid in ($userid1, $userid2)
group by groupid
having count(distinct userid) = 2;

如果您愿意,可以将其转换为布尔值:

select (case when count(*) > 0 then true else false end)
from (select groupid
      from table t
      where userid in ($userid1, $userid2)
      group by groupid
      having count(distinct userid) = 2
     ) g;

答案 2 :(得分:0)

UNIQUE userid

每个用户最多只能有一个条目(如问题似乎要问)。

SELECT (SELECT groupid FROM tbl WHERE userid = 5)
     = (SELECT groupid FROM tbl WHERE userid = 6);

假设useridUNIQUE 完全按照要求返回TRUEFALSE - 或NULL如果找不到useridgroupid为NULL。

UNIQUE (userid, groupid)

每个用户只能有多个条目(如评论中所述):

分享所有群组?

SELECT EXISTS (
   SELECT 1
   FROM      (SELECT groupid FROM tbl2 WHERE userid = 5) a
   FULL JOIN (SELECT groupid FROM tbl2 WHERE userid = 6) b USING (groupid)
   WHERE a.groupid IS NULL OR
         b.groupid IS NULL
   ) AS share_all;

至少分享一个小组?

SELECT EXISTS (
   SELECT groupid FROM tbl2 WHERE userid = 8
   INTERSECT
   SELECT groupid FROM tbl2 WHERE userid = 9
   ) AS share_min_one;

或者

SELECT EXISTS (
  SELECT 1
  FROM  (SELECT groupid FROM tbl2 WHERE userid = 5) a
  JOIN  (SELECT groupid FROM tbl2 WHERE userid = 6) b USING (groupid)
  ) AS share_min_one;

只分享一个小组?

SELECT count(*) = 1 AS share_exactly_one
FROM  (SELECT groupid FROM tbl2 WHERE userid = 5) a
JOIN  (SELECT groupid FROM tbl2 WHERE userid = 6) b USING (groupid);

SQL Fiddle有更好的测试数据。

所有这些查询都很快,userid上有索引。 Postgres 9.2 +中的(userid, groupid) multicolumn index更快。

最终这是的情况。这是一个查询技术库: