AB Vyas
AB Vyas

Reputation: 2389

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

Upvotes: 0

Views: 163

Answers (2)

Ahmad
Ahmad

Reputation: 12737

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

Upvotes: 1

bummi
bummi

Reputation: 27385

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

Upvotes: 3

Related Questions