SQL其中,同时保留他们

问题描述:

幸福感值存在,我有2个表是这样的:

表1SQL其中,同时保留他们

ID | USER_ID 
1 0  
2 2  
3 15  
4 16  

表2

ID | FROM | TO 
9 0  2 
9 2  16 
9 16  15 
9 15  0 
10 15  2 

我想是非常简单的,但我都快疯了,考虑到ID,FROMTO代表表2中的用户。我想要FROM(这是Table1.user_id)中的某人ID在表2中,例如它也是existsTO(这是相同的Table1.user_id)与表2相同ID

例如,记录16是合格的。因为它出现在从9 IDTO用9同ID表2(两者并从对应于15 table1中为user_id)

我所做的是:

select * 
from `Table1` 
where exists (select ID from `Table2` as p1 where FROM = 16) 
     and exists (select ID from `Table2` as p2 where ID = 16) 
     and p1.ID = p2.ID 

这可能工作;

select * from table1 a where a.USER_ID in 
(select b.FROM from table2 b 
where exists (select c.id from table2 c 
where b.id = c.id and b.FROM = c.TO)) 
+0

我已经更新的问题,更多的细节。请检查 – 2015-02-06 22:59:14

这是你想要的吗?

select * 
from table1 t 
where exists (select 1 from table2 t2 where t2.`from` = t.id) and 
     exists (select 1 from table2 t3 where t3.`to` = t.id); 
+0

他们是两个表而已,一个我们得到主要的id从(代表FROM和TO在2个不同的记录中)和另一个表(x)包含FROM,TO,ID ...因此,我想获得表格(x)ID – 2015-02-06 22:52:56

+0

@ Naughty.Coder。 。 。这确实不会改变查询背后的想法。我做了改变。 – 2015-02-06 23:21:17

你可以尝试使用self join找到具有相同ID的记录,然后比较这两个值。

select a.from from table1 a inner table1 b on a.id = b.id 
where a.from = b.to 
+1

'哪里'也可以替换为'和' – Kevin 2015-02-06 23:05:31

我不确定如果理解正确。

如果User_IDTable_1应该出现在From和从TABLE_2 To列,这些记录也ID在Table_2必须是相同的,

那么对于这些​​条件将有资格不仅User_ID 16和15为您在你的例子中提到但也为0和2.

假设这是正确的。

那就试试这个代码(MySQL中,你可能要改变一些语法):

SELECT A.* 
FROM Table_1 AS A 
INNER JOIN Table_2 AS B ON (A.USER_ID=B.FROM) 
INNER JOIN Table_2 AS C ON (A.USER_ID=C.TO AND C.ID = B.ID)