0

我的数据库中有两个表。

1) User Table

id  username    password    logo    email
1   admin        admin      NULL    1   
2   support     support     NULL    NULL    
3   test        test        NULL    NULL    


2) Link Account Table

ID  AccountID   LinkAccountID
1       1           2

现在,如果我选择带有 accountid 1 的用户名,那么如果我选择带有 accountid 2 的用户名,它会以同样的方式返回我 Admin 和 Support,那么它也会返回 admin 和 support,如果我选择带有 accountid 3 的用户名,那么它将只返回 test

反之亦然,如果在链接帐户表帐户 id 为 1 或 linkaccountid 为 1 将返回两个 id

提前致谢

问候

阿米特维亚斯

4

2 回答 2

3
Select u.id,u.Name
from user u
left join
(
Select AccountID as AID , LinkAccountID as sec from Account
union
Select LinkAccountID as AID,AccountID  as sec from Account
) a 
on a.AID=u.ID

where @SearchUser in (Coalesce(a.Aid,u.id),Coalesce(a.Sec,u.id)) 
于 2012-11-06T08:17:08.777 回答
1

Assuming you can manage to change @SearchID to whatever ID you want to search for, then this is one way to do it

select * from users a
where a.id = @SearchID

or
 a.id in (
    select b.AccountID from link_account b where b.LinkAccountID = @SearchID
         union 
    select b.LinkAccountID from link_account b where b.AccountID = @SearchID);

I have tried it and it is working.

Here is the Fiddle for that http://sqlfiddle.com/#!3/738b7/110

于 2012-11-06T08:04:28.620 回答