如何在JOIN中引用外部字段?

时间:2018-06-18 08:43:04

标签: sql sqlite join

这是我的架构: enter image description here

我需要选择所有具有最优先级的手机和地址的用户。这是为特定用户选择最具优先级的电话的查询(id = 1):

select ph.id, ph.number from VisitingCard vc
left join Phone ph on ph.card_id = vc.id
where vc.person_id = 1
order by priority desc
limit 1

以下是我尝试为所有用户获取最优先的手机:

select * from Person p
left join (
    select ph.id, ph.number from VisitingCard vc
    left join Phone ph on ph.card_id = vc.id
    where vc.person_id = p.id -- no such column: p.id
    order by priority desc
    limit 1
)

Link - SqlFiddle with schema和用户最优先的地址和电话(id = 1)

如何为每个用户使用此类查询,但不仅适用于id = 1的用户?

2 个答案:

答案 0 :(得分:1)

一种方法使用相关子查询:

select vc.person_id,
       (select ph.number
        from Phone ph 
        where ph.card_id = vc.id
        order by ph.priority desc
        limit 1
       ) as number
from VisitingCard vc;

答案 1 :(得分:0)

使用相关子查询查询具有优先级地址和电话的每个用户 (感谢this answer)的想法:

select p.*,
(
    select ph.number
    from VisitingCard vc
    left join Phone ph on ph.card_id = vc.id
    where vc.person_id = p.id
    order by ph.priority desc, ph.id asc
) as most_prioritized_number,
(
    select ad.address_text
    from VisitingCard vc
    left join Address ad on ad.card_id = vc.id
    where vc.person_id = p.id
    order by ad.priority desc, ad.id asc
) as most_prioritized_address
from Person p

SqlFiddle