我想根据表2中的两个不同字段从表1中检索两个不同的名称?

cidc1ykv  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(238)

我有两个表“phonebook”和“phonecall”,我想根据callfrom和callto在phonebook中查找姓名。
我的代码为这两个字段返回相同的名称,因为我只引用callto字段,不能包含callfrom字段。

SELECT 
    phonecall.callDate, 
    phonecall.callTime, 
    phonecall.callFrom, 
    phonebook.personFirstname as First, 
    phonebook.personLastname as Last, 
    phonecall.callTo, phonebook.personFirstname First1, 
    phonebook.personLastname as Last1, 
    phonecall.callDuration
FROM phonecall 
LEFT JOIN phonebook on 
    callTo = phonebook.personService
WHERE 1
ORDER BY phonecall.callDate, phonecall.callTime

此代码失败:

SELECT 
    phonecall.callDate, 
    phonecall.callTime, 
    phonecall.callFrom, 
    phonebook.personFirstname as First, 
    phonebook.personLastname as Last, 
    phonecall.callTo, 
    phonebook.personFirstname as First1, 
    phonebook.personLastname as Last1, 
    phonecall.callDuration
FROM phonecall 
LEFT JOIN phonebook on 
    phonecall.callTo = phonebook.personService
LEFT JOIN phonebook on 
    phonecall.callFrom = phonebook.personService
WHERE 1
ORDER BY phonecall.callDate, phonecall.callTime

我知道这可能很简单,但我的sql经验非常有限,没有找到任何示例。

k3bvogb1

k3bvogb11#

这不是一个完整的解决方案,但只是演示了如何在不同的条件下连接同一个表两次,然后从每个表返回列。

SELECT 
    phonecall.callDate, 
    phonecall.callTime, 
    phonecall.callFrom, 
    `callfr`.personFirstname as First, 
    `callfr`.personLastname as Last, 
    phonecall.callTo, 
    `callto`.personFirstname as First1, 
    `callto`.personLastname as Last1, 
    phonecall.callDuration
FROM phonecall 
LEFT JOIN phonebook `callto`
    on phonecall.callTo = `callto`.personService
LEFT JOIN phonebook `callfr`
    on phonecall.callFrom = `callto`.personService
WHERE 1
ORDER BY phonecall.callDate, phonecall.callTime

相关问题