sql加入如何连接多个表

时间:2014-03-21 20:24:24

标签: sql join

我有3个表:药物订单,订单目录和人

medicationOrder (
    startdate, 
    enddate,
    catalogId,
    orderId,
    personId)    

ordercatalog (
    catalogId, 
    drugId,
    IsGeneric,
    Brand)

Person (firsstname,
    lastname, 
    dob,
    personId)

我想检索姓氏为“猫”的患者的所有药物订单......我试过了..你能不能告诉我哪里出错...谢谢..

select *
from ordercatalog as o, person as p, medicationorder as m

join ordercatalog on o.CatalogId= m.CatalogId, 

where (p.PersonId= m.PersonId and p.LastName= "Cat");

3 个答案:

答案 0 :(得分:1)

            SELECT * FROM 
            ORDERCATALOG O INNER JOIN MEDICATIONORDER M
            ON O.CATALOGID=M.CATALOGID
            INNER JOIN PERSON P
            ON P.PERSONID=M.PERSONID 
            AND P.LASTNAME='CAT';

答案 1 :(得分:1)

试试这个: -

 select * from medicationorder m 
inner join person p on p.PersonId = m.PersonId
inner join ordercatalog o on m.CatalogId=o.CatalogId where p.LastName = 'Cat';

希望它会对你有所帮助。

答案 2 :(得分:0)

您已经结合了两种不同的SQL标准。

旧标准称为SQL89:

select 
  *
from 
  ordercatalog as o, 
  person as p,
  medicationorder as m
where
  o.CatalogId= m.CatalogId
  and p.PersonId= m.PersonId 
  and p.LastName= "Cat"

请注意,所有联接都在where子句中处理。

相反,您可以根据SQL92标准执行此操作,该标准将您的联接放在from子句中:

select
    *
from
    ordercatalog o
    inner join medicationorder m on o.CatalogId = m.CatalogId
    inner join person p on m.PersonId = p.PersonId and p.LastName = "Cat"

您应该会发现,目前所有平台都支持SQL92标准。但大多数人都支持两者。