SQL匹配多行

时间:2012-06-29 09:34:03

标签: sql-server relation

relationID     sessionID_Ref     userID_Ref
1              1                 1
2              1                 2
3              2                 1
4              2                 3
5              3                 1
6              3                 2
7              3                 3

奥基!我正在建立一个消息系统,可以向一群人发送消息。但是我坚持使用这个SQL查询,根据我发送消息的用户来查找sessionID。

例如:如果我(userID:1)向userID 2发送消息,则SQL Query应返回sessionID:1

如果我向userID 2和3发送消息,它将返回:sessionID:3

我可以使用MSSQL进行单个SQL查询吗?

2 个答案:

答案 0 :(得分:3)

可能是这样的:

select sessionID_Ref
from tablename
group by sessionID_Ref
having count(distinct userID_Ref) = 2
   and min(userID_Ref) = 1
   and max(userID_Ref) = 2

以下是一个完整的例子:

create table #tablename (
    relationID int,
    sessionID_Ref int,
    userID_Ref int
)

insert into #tablename values(1,1,1)
insert into #tablename values(2,1,2)
insert into #tablename values(3,2,1)
insert into #tablename values(4,2,3)
insert into #tablename values(5,3,1)
insert into #tablename values(6,3,2)
insert into #tablename values(7,3,3)


create table #users (
    users int
)

insert into #users values(1)
insert into #users values(3)


select t.sessionID_Ref from #tablename t
inner join #users u on t.userID_Ref = u.users
inner join (
    select t.sessionID_Ref
    from #tablename t
    group by t.sessionID_Ref
    having COUNT(t.userID_Ref) = (select COUNT(*) from #users)
) aux on aux.sessionID_Ref = t.sessionID_Ref
group by t.sessionID_Ref
having COUNT(t.userID_Ref) = (select COUNT(*) from #users)


drop table #tablename
drop table #users

答案 1 :(得分:0)


    SELECT TOP 1    sessionID_Ref
    FROM         table AS table_2
    WHERE     (userID_Ref = 28 OR
                          userID_Ref = 11) AND
                              ((SELECT     COUNT(*) AS Expr1
                                  FROM         table AS table_1
                                  WHERE     (sessionID_Ref = table_2.sessionID_Ref) AND (userID_Ref = 28) OR
                                                        (sessionID_Ref = table_2.sessionID_Ref) AND (userID_Ref = 11)) = 2) AND
                              ((SELECT     COUNT(*) AS Expr1
                                  FROM         table AS table_1
                                  WHERE     (sessionID_Ref = table_2.sessionID_Ref)) = 2)

这样可行,但必须有更快的方法......