如何按值列表查询表?

时间:2017-03-08 20:13:54

标签: sql postgresql

我有3张桌子:

Person
-----------
id
name
doctor_id

Doctor
-----------
id
name

Person_Doctor
-------------
id
person_id
doctor_id

这个想法是一个人可以有一个以上的医生,一个医生可以有一个以上的病人(人)。

我想做的是通过id获取所有人的医生。这是我的预备策略:

SELECT * FROM Person_Doctor WHERE person_id=:id

然后通过Person_Doctor将每个doctor_id映射到相应的医生。这种方法的事情是我将不得不为每个Person_Doctor对象查询数据库,看起来很昂贵。有更好的方法吗?

3 个答案:

答案 0 :(得分:1)

Select p.name as patient, d.name as doctor
From person as p inner join person_doctor as pd on pd.person_id = id
                 inner join doctor as d on pd.doctor_id = d.id
where p.id = SomeID

答案 1 :(得分:0)

这是一个相当基本的JOIN,它是关系数据库的基本元素。一旦你完成了这项任务,我就会建议你学习并在数据库中修读大学课程。在SQL中工作时遇到的问题都比这更难。

SELECT d.name as 'doctor name' 
FROM doctor d
    INNER JOIN person_doctor pd on d.doctor_id = pd.doctor_id
    INNER JOIN person ON p p.person_id = pd.person_id
WHERE p.person_id = @id

答案 2 :(得分:0)

SELECT DISTINCT p.id
FROM person p 
        join person_doctor pd 
            on p.id = pd.person_id 
        join doctor d 
            on pd.doctor_id = d.id
WHERE p.doctor_id IS NOT NULL