[英]Get all from left table event if there is nothing in join table
這是診所的表結構, 具有許多類別 :
Clinic Category
id company_id | clinic_id | type
--- -----------------------------
1 -> 1 | 1 | pre
2 | 1 | pre
2 -> 1 | 2 | ext
2 | 2 | ext
3 -> 1 | 3 | pre
4 -> 2 | 4 | ext
5 -> 2 | 5 | pre
在這里,我想讓所有診所的輸出先按pre pre然后ext排序。 但是,有時我需要根據company_id檢查條件( eg: 1, in the following try
),並且我不希望診所被過濾掉。
我的嘗試
Clinic.joins("LEFT JOIN categories c ON c.clinic_id = clinics.id").
order("
CASE c.type
WHEN 'pre' THEN 0
WHEN 'ext' THEN 1
ELSE 2
END
").
where("c.company_id = 1 OR c.company_id IS NULL")
問題是,從表結構中可以看出,如果我沒有一家診所與公司ID為1
的類別匹配,它將被過濾掉,但是,我仍然希望該診所成為其他類型的輸出的一部分。
公司ID的預期輸出= 1
Clinic Category
id company_id | clinic_id | type
--- -----------------------------
1 -> 1 | 1 | pre
3 -> 1 | 3 | pre
2 -> 1 | 2 | ext
4 -> NULL | NULL | NULL(or other)
5 -> NULL | NULL | NULL(or other)
公司ID的預期輸出= 2
Clinic Category
id company_id | clinic_id | type
--- -----------------------------
1 -> 2 | 1 | pre
5 -> 2 | 5 | pre
2 -> 2 | 2 | ext
4 -> 2 | 4 | ext
3 -> NULL | NULL | NULL (or other)
在left join
的company_id
自身中,如下所示過濾company_id
LEFT JOIN categories c ON c.clinic_id = clinics.id AND c.company_id = 1
希望這對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.