简体   繁体   中英

How can i make a query of two different objects in the same column of one table, relationed to different columns in another table?

I have the tables

people

id INTEGER

name

phone_number

PRIMARY KEY(id)

phone_calls

id INTEGER

caller_number

receiver_number

year

month

day

duration

PRIMARY KEY(id)

I want to take the information like

name1 (as caller) name2 (as receiver)
nikolas mary
kostas bob

i managed with SELECT name, caller_number FROM people JOIN phone_calls ON people.phone_number = phone_calls.caller_number WHERE year = AND month = AND day = AND duration =; to get

name as caller caller_number
nikolas 6999999999
kostas 688888888

or with SELECT name, receiver_number FROM people JOIN phone_calls ON people.phone_number = phone_calls.receiver_number WHERE year = AND month = AND day = AND duration =; to get

name as receiver receiver_number
mary 6777777777
bob 6555555555

or with SELECT caller,receiver_number FROM phone_calls WHERE year = AND month = AND day = AND duration; to get

caller_number receiver_number
6999999999 6777777777
688888888 6555555555

or with SELECT name, receiver_number FROM people JOIN phone_calls ON people.phone_number = phone_calls.caller_number WHERE year = AND month = AND day = AND duration =; to get

name as caller receiver_number
nicolas 6777777777
kostas 6555555555

so i get the name at the telephone number of the caller or the name and the telephone number of the receiver, but not name of the caller and name of the receiver in the same place.

You need 2 joins to get both caller and receiver's name. For example

SELECT caller.name, receiver.name
FROM phone_calls
JOIN people caller ON caller.phone_number = phone_calls.caller_number
JOIN people receiver ON receiver.phone_number = phone_calls.receiver_number
WHERE <your conditions>

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