SQL Server:在具有可互换值的两列上记录过滤器

时间:2015-03-11 17:06:41

标签: sql sql-server

我有一张包含以下数据的表格:

pkId      FromUserId         ToUserID     Message
----------------------------------------------------------------
1         100                101          Hello 101
2         101                100          Hi 101
3         102                100          hello 100 from Me,102 

我想从FromUserId不等于ToUserIDToUserID不等于其他行的FromUserId的表中获得一条记录,例如:

pkId      FromUserId         ToUserID     Message
----------------------------------------------------------------
2         101                100          Hi 101
3         102                100          hello 100 from Me,102 

如何在SQL Server中实现?

3 个答案:

答案 0 :(得分:0)

首先声明一个变量表(不是临时表)

DECLARE @table table(
    id INT NOT NULL,
    from VARCHAR(100),
    to VARCHAR(100)
);

然后只添加您想要该表的行的id

INSERT INTO @table
    SELECT pkId, FromUserId, ToUserID
    FROM TABLE1 
    WHERE FromUserId <> ToUserID
    GROUP BY pkId, FromUserId, ToUserID

然后选择您的结果

SELECT t1.pkId, t1.FromUserId, t1.ToUserID, t1.Messagge
FROM TABLE1 t1
INNER JOIN @table t0
ON t1.pkId = t0.id

答案 1 :(得分:0)

select * from table2 where pkid in
(
select MAX(pkid) from table2 where (fromuserid in (select touserid from
[table2]) and touserid in (select fromuserid from [table2]))
)
or pkid in
(
select pkid from table2 where (fromuserid not in (select touserid from
[table2]) or touserid not in (select fromuserid from [table2]))
)

答案 2 :(得分:-2)

select * from table1 where fromuserid not in
(select touserid from table1)
and 
touserid not in
(select fromuserid from table1)

select * from [123] where ToUserID = 100