关系部门:确切部门

时间:2016-09-13 02:56:01

标签: sql postgresql activerecord relational-division

我遇到了以下问题:

  

编写查询以查找与其他用户U完全相同的朋友。

以下是表格(和一个SQL小提琴:http://sqlfiddle.com/#!9/457260/1):

  • 用户:
    • user_id:Int
  • 友谊:
    • user_id:Int
    • friend_id:Int

我的查询问题是它返回的用户拥有相同的朋友或超过用户U.

    Function DeleteCol(iCol As Integer, strCriteria As String, strWSName As String, bPositive As Boolean)

  Dim iLastCol As Integer
  Dim wsUsed As Worksheet

  Set wsUsed = ThisWorkbook.Worksheets(strWSName)
  iLastRow = wsUsed.Cells(Rows.Count, iCol).End(xlUp).Row
  For i = iLastRow To 1 Step -1
    With wsUsed.Cells(i, iCol)
      If bPositive Then
        If .Value = strCriteria Then .EntireRow.Delete
      Else
        If .Value <> strCriteria Then .EntireRow.Delete
      End If
    End With
  Next i

End Function

1 个答案:

答案 0 :(得分:1)

最简单的方法是聚合朋友,然后进行比较:

with f as (
      select user_id, array_agg(friend_id order by friend_id) as friends
      from friendships f
      group by user_id
     )
select user_id
from f
where f.friends = (select friends from f where user_id = 1) and
      f.user_id <> 1;