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
,FROM
和TO
代表表2中的用户。我想要FROM
(这是Table1.user_id)中的某人ID
在表2中,例如它也是exists
在TO
(这是相同的Table1.user_id)与表2相同ID
例如,记录16是合格的。因为它出现在从9 ID
和TO
用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))
这是你想要的吗?
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);
他们是两个表而已,一个我们得到主要的id从(代表FROM和TO在2个不同的记录中)和另一个表(x)包含FROM,TO,ID ...因此,我想获得表格(x)ID – 2015-02-06 22:52:56
@ Naughty.Coder。 。 。这确实不会改变查询背后的想法。我做了改变。 – 2015-02-06 23:21:17
我不确定如果理解正确。
如果User_ID
从Table_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)
我已经更新的问题,更多的细节。请检查 – 2015-02-06 22:59:14