Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting with two references to same table

Tags:

sql

sql-server

Maybe I have a bad design but I am currently trying to get an ordering system for a small store up and running. As it is a gift order can have a sender and recipient to show where and from an order is going.
So we have table

Person
personid
name 
address

Order
Sender_personid
Receiver_personid
etc...

I am having trouble creating a sql statement to select the names and address of both people in an order. If this can be done any pointers would be great. If not any design pointers equally apreciated.

like image 902
BastanteCaro Avatar asked Dec 15 '25 12:12

BastanteCaro


2 Answers

I think you want something like this:

SELECT
    SP.*,
    RP,*,
    O.*
FROM Order O
JOIN Person SP ON SP.PersonID = O.Sender_PersonID
JOIN Person RP ON RP.PersonID = O.Receiver_PersonID

Just join on the table twice.

like image 53
rsbarro Avatar answered Dec 17 '25 02:12

rsbarro


Basically you just do the same as if you just wanted to get 1 person (say, only the receiver), but this time you join the table twice. Table aliases can help understanding

SELECT receiver.name, sender.name
FROM order o, person as receiver, person as sender
where o.sender_personid = receiver.personid 
and o.sender_personid = sender.personid
like image 44
Konerak Avatar answered Dec 17 '25 01:12

Konerak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!