2

我有 3 张桌子:

Create table users (
    id Number NOT NULL ,
        groupID Number NOT NULL ,
    name Varchar2(50),
primary key (id) 
);

Create table friends (
    friendID Number NOT NULL ,
    user_a Varchar2(35),
    user_b Varchar2(35),
primary key (friendID) 
);

Create table groups (
    groupID Number NOT NULL ,
    gname Varchar2(35),
primary key (groupID) 
);

Alter table users add  foreign key (groupID) references groups (groupID);

嵌入数据:

Users table
id | groupid | name
--------------------
1  |    1    |   s1
2  |    3    |   s2
3  |    2    |   s3
4  |    1    |   s4
5  |    2    |   s5

friends table
friendID | user_a | user_b
--------------------------
1        |   1    |   2
2        |   3    |   1
3        |   4    |   2
4        |   5    |   3
5        |   2    |   5

groups table 
groupid | groupname
--------------------
   1    |     in01
   2    |     in02
   3    |     in03

我想运行这个查询:任何组之间的关系最多?这是我当前的查询,但它不起作用

SELECT g.gname ,count(a.aname) as con
FROM users a
left join group g on g.groupid=a.groupid
left join friends f on f.user_a=a.id
group by con;
4

1 回答 1

1

怎么样:

Select gname1, gname2, count(*) cnt
    from (
Select least(g1.gname, g2.gname) gname1,
         Greatest(g1.gname, g2.gname) gname2
   From friends f
   Join users u1 on f.user_a = u1.id
   Join users u2 on f.user_b = u2.id
   Join groups g1 on g1.groupid = u1.groupid
   Join groups g2 on g2.groupid = u2.groupid
) gc
Group by gname1, gname2
Order by count(*) desc

子查询中的最小和最大函数用于避免 g1,g2 和 g2,g1 有两个条目。

这将为您提供组之间关系的计数。请注意,它将包括相同组之间的关系,如果您不希望始终添加 where 子句

 Where u1.groupid != u2.groupid
于 2013-05-26T12:10:23.647 回答