选择在相同列(未知)值上相等的所有行

时间:2013-02-28 22:05:35

标签: sql

我的表列出了x个用户之间的线程。每个用户都可以在y个线程中。

下面,user_id 1位于主题12中,依此类推......

现在,我们只说user_id 1,我怎样才能获得与thread_id {{1}行相同user_id的所有行}?

1

毫无头绪......


修改

给定 id user_id thread_id 1 1 1 2 1 2 3 2 1 4 3 2 s 1和2.现在给我一个只有两个共享的thread_id。我不想要1和2的所有线程,而只需要它们共享的线程。

5 个答案:

答案 0 :(得分:2)

如果要查找具有完全相同线程集的用户对,则以下查询将起作用:

select t.user_id, t2.user_id
from (select t.*, count(*) over (partition by t.user_id) as NumThreads
      from t
     ) t left outer join
     t t2
     on t.thread_id = t2.thread_id and t.user_id <> t2.user_id
group by t.user_id, t2.user_id
having SUM(case when t.user_id is null then 1 else 0 end) = 0 and
       SUM(case when t2.user_id is null then 1 else 0 end) = 0 and
       count(*) = max(t.NumThreads)

在这个查询中,无论它在哪里说“从t t2”,你都会把“从t2”。如果该行是“从t”,你会把“从t”。

此查询的结构是具有聚合的自联接。打算找到每对匹配的线程。然后通过两个user_ids对它们进行分组。如果匹配线程的数量是用户的线程数(第三个条件)没有线程匹配(前两个条件),则两个用户匹配所有线程。 / p>

关于所有用户的线程评论中的问题更容易。

select thread_id
from t cross join
     (select count(distinct user_id) as NumUsers from t) const
group by thread_id
having count(*) = max(const.NumUsers)

答案 1 :(得分:1)

declare @id int
set @id = (select thread_id from threads where user_id = 1)

select * from threads where thread_id = @id

答案 2 :(得分:1)

SELECT * FROM table
WHERE user_id!=1 AND
      thread_id IN (SELECT thread_id FROM table WHERE user_id=1);

基于Indianer编辑的问题描述的新答案:

SELECT * FROM table t1
JOIN table t2 ON t1.thread_id=t2.thread_id AND t1.user_id!=t2.user_id
WHERE t1.user_id IN (1,2) AND t2.user_id IN (1,2);

答案 3 :(得分:1)

select distinct thread_id from tableX
where thread_id in (select thread_id from tableX where user_id=1)
and thread_id in (select thread_id from tableX where user_id=2)

我修改了我的答案以符合您的评论澄清。试一试。

答案 4 :(得分:1)

您可以使用EXISTS

DECLARE @userID INT 
SET @userID = 1 

SELECT u1.id, u1.user_id, u1.thread_id 
FROM   userthreads u1 
WHERE  u1.userid <> @userId 
       AND EXISTS(SELECT 1 
                  FROM   userthreads u2 
                  WHERE  u2.userid <> u1.userid 
                         AND u2.threadid = u1.threadid)

DEMO

如果要包含具有给定用户ID的用户,请省略WHERE u2.userid <> u1.userid