简体   繁体   中英

select data vice versa

I have two table in my database.

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

Now if i select username with accountid 1 then it will return me Admin and Support same way if i select username with accountid 2 then also it will return admin and support and if i select username with accountid 3 then it will return only test

something like vice versa if in link account table account id is 1 or linkaccountid is 1 that will return both id

Thanks in advance

Regards

Amit Vyas

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)) 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM