簡體   English   中英

使用字段數據進行條件JOIN

[英]Conditional JOIN using field data

我有以下表格:

dogid, name, event_id用於存儲狗的id, name, event_id

eventid, title, owner_id ,用於存儲生日,疫苗等事件

ownerid, name用於存儲所有者的名稱。 原始所有者是ID為1的狗窩

owner_eventoriginal_owner_event_id, other_owner_event_id ,用於將各種所有者事件彼此等同,即原始所有者可能認為“步行事件”與另一個所有者的“比賽接球”事件相同。


加入一切:

加入事件 ,其中dog.event_id = event.id

所有者加入事件 ,其中event.owner_id = owner.id

這是棘手的部分

owner_id > 1 事件將加入owner_event ,其中owner_event.other_owner_event_id = event.id

否則, 事件將加入owner_event ,其中owner_event.original_owner_event_id = event.id


到目前為止,我有以下內容:

SELECT * FROM dog
LEFT JOIN event `event` ON `event`.id = dog.event_id
LEFT JOIN owner `owner` ON `owner`.id = `event`.owner_id
LEFT JOIN owner `owner_event_other` ON `owner_event_other`.other_owner_event_id = `event`.id AND `owner`.id > 1
LEFT JOIN owner `owner_event_original` ON `owner_event_original`.original_owner_event_id = `event`.id AND `owner`.id = 1
WHERE dog.id = 3

我只是不確定如何立即獲得狗3event.title (例如)。

銘記,這可能是event.idowner_event.other_owner_event_id列或owner_event.original_owner_event_id列取決於owner.id

由於只有兩個可能性,對於給定存在一個owner的記錄,我建議只加入owner_event一次,但鏈event第二次將它,以便檢索經原主人的事件的標題(如果直接檢索到的event記錄不代表該標題。使用COALESCE您可以選擇正確的標題。

SELECT    dog.*,
          COALESCE(original_event.title, event.title) AS original_event_title 
FROM      dog
LEFT JOIN event 
       ON event.id = dog.event_id
LEFT JOIN owner 
       ON owner.id = event.owner_id
LEFT JOIN owner_event
       ON owner_event.other_owner_event_id = event.id
LEFT JOIN event original_event
       ON original_event.id = owner_event.original_owner_event_id
WHERE     dog.id = 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM