开发者

Basic SQL join query

开发者 https://www.devze.com 2023-01-11 10:39 出处:网络
I have a few tables: event_type (et), event (e), event_booking (eb), person (p), person_address (p) and address_country (ac)

I have a few tables:

event_type (et), event (e), event_booking (eb), person (p), person_address (p) and address_country (ac)

They are joined like so:

et <- e <- eb -> p -> pa -> ac

Every join has a one-to-one relationship, except the eb -> p link. A row in eb can have a null instead of an id from p.

I want to get all bookings, regardless of whether there's a corresponding row in p.

So, a simple left join.

but which would be better? (or is there a better way?)

et J e J eb LJ p LJ pa LJ ac (I'm assuming this would be treated identically to 开发者_运维技巧ac J pa J p RJ eb RJ e RJ et?)

or

et J e J eb LJ (p J pa J ac) (i.e. left join a sub-select)


I usually use the following syntax - which somehow corresponds to your second scenario

select
    *
from 
    eb
    inner join e on eb.eId = e.eId
    inner join et on e.etId = et.etId
    left join p
           inner join pa on p.paId = pa.paId
           inner join ac on pa.acId = ac.acId
        on eb.pId = p.pId

I am not sure about the performance implications but I would not be surprised if both scenarios generated the same query plan


Just test your queries using EXPLAIN, it will show if and how keys are used.

0

精彩评论

暂无评论...
验证码 换一张
取 消