2016-02-26 83 views
1

我不知道我是否没有考虑正确的连接结构,但似乎无法从此连接中获得我想要的结果。在sql连接之后排除查询表中的数据

这是我这3个表

select target, sender, message, amount, transactiontime, transaction_id 
from transactions 
join accounts on transactions.sender=accounts.account_id 
join users on users.user_id=accounts.user_id 
where users.user_id=40 
union 
select target, sender, message, amount, transactiontime, transaction_id 
from transactions 
join accounts on transactions.target=accounts.account_id 
join users on users.user_id=accounts.user_id 
where users.user_id=40 
order by transactiontime 
limit 20; 

SQL result table

这是我有查询,并将其通过3个表查询的SQL模式。基本上我只需要来自我的交易表的信息,但我想排除任何不与该用户关联的account_id。在这种情况下,用户ID是40,他们的account_id是57.想知道如何才能摆脱这种情况。基本上如何让3不出现。另外作为奖励,将查询的结构包括id与我的账户相关联。就像account_id 4和57属于一个用户,并且钱在他们之间流动一样。我如何能够在我的交易查询表中看到4和57?

+0

我不明白这一点。您显示的是用户40的前20个交易,无论通过他们的哪个账户,无论是作为发件人还是收件人。这不是你想要的吗?你还想要什么?如果您向我们展示您获得的结果与您期望的结果(以及文本请不要作为图片链接),这可能会有所帮助。 –

回答

0

为“排除关联到该用户的任何ACCOUNT_ID”, ,就等于说“仅包含帐户绑定该用户”?

declare @user_id int = 40 

select target, sender, message, amount, transactiontime, transaction_id 
from transactions 
join accounts on transactions.sender=accounts.account_id 
       OR transactions.target=accounts.account_id 
where [email protected]_id 

如果目标是只看到账户的交易双方(发送器和目标)属于同一用户:如果你想要的所有信息,从您的交易表的

declare @user_id int = 40 

select target, sender, message, amount, transactiontime, transaction_id 
from transactions 
join accounts as send on transactions.sender=send.account_id 
join accounts as targ on transactions.target=targ.account_id 
where [email protected]_id 
and [email protected]_id 
+0

是的,所以我不想要任何不属于该用户的帐户,该查询也将显示其他用户的account_id信息 –

+0

此查询为您提供属于该用户的帐户是发件人或目标。另一个用户的帐户可能或可能是任何给定交易中的发件人/目标副本。 –

+0

目标是仅获得属于同一用户的帐户之间的交易吗? (编辑答案) –

0

给定用户ID:

select 
    * 
from 
    transactions 
where 
    transactions.user_id = 40 

应该足够了。您不需要union语句再次对同一个查询或加入到用户表。

如果要列出所有的帐户ID为这些事务将要的人,你可以使用:

select 
    target, sender, message, amount, transactiontime, transactions.transaction_id, accounts.account_id 
from 
    transactions 
inner join 
    accounts 
on 
    transactions.target = accounts.user_id