在 sql 加入后从查询的 table 中排除数据

Excluding data from a queried table after sql join

我不知道我是否没有考虑正确的连接结构,但我似乎无法从该连接中获得我想要的结果。

这是我的 sql 这 3 table 的架构

schema

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 table 秒。基本上我只想要来自我的交易 table 的信息,但我想排除任何与该用户无关的 account_id。在这种情况下,用户 ID 是 40,他们的 account_id 是 57。想知道我怎样才能摆脱它。基本上如何让 3 不出现。另外作为奖励,包含与我的帐户关联的 id 的查询结构是什么。就像 account_id 4 和 57 属于一个用户并且资金在他们之间流动一样。我如何才能在交易查询中同时看到 4 和 57 table?

排除任何account_id与该用户关联”, 那不是说"Include only accounts associated to that user"吗?

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 accounts.user_id=@user_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 send.user_id=@user_id 
and   targ.user_id=@user_id 

如果您想要给定用户 ID 的交易 table 中的所有信息:

select 
    *
from 
    transactions
where 
    transactions.user_id = 40 

应该够了。您不需要再次对同一查询使用 union 语句或加入用户 table.

如果您想列出这些交易的收件人的所有帐户 ID,您可以使用:

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