[英]Joining a variable number of tables based on column value
我的代碼中有一些模型,該模型在以下結構的MySQL數據庫中建模:
Properties
+----+------+---------+
| id | name | address |
|----+------+---------|
| 1 | p1 | 123 st |
| 2 | p2 | 123 st |
| 2 | p3 | 123 st |
+----+------+---------+
Tenants (belongs to property)
+----+-------------+-------+
| id | property_id | suite |
|----+-------------+-------|
| 1 | 1 | s1 |
| 2 | 1 | s2 |
| 3 | 2 | s3 |
+----+-------------+-------+
Costs (can belong to property or tenants)
+----+--------------+-----------+--------------+
| id | parent_model | parent_id | name |
|----+--------------+-----------+--------------+
| 1 | property | 1 | gardening |
| 2 | property | 2 | construction |
| 3 | tenant | 1 | renovation |
+----+--------------+-----------+--------------+
Files (can belong to any model)
+----+--------------+-----------+--------------+
| id | parent_model | parent_id | name |
|----+--------------+-----------+--------------+
| 1 | property | 1 | file1.jpg |
| 2 | tenant | 2 | file2.pdf |
| 3 | costs | 3 | file3.doc |
+----+--------------+-----------+--------------+
從表結構可以看出,所有模型都可以鏈接回property
記錄(直接或通過一個或多個中間表)。
在我的代碼中,我想編寫一個查詢來獲取file
的property.id
。看完這個問題之后: 基於列值連接不同的表,我意識到可以通過以下方法找到從file
到property
的“鏈接”很少加入。
所需的聯接數根據parent_model
不同而不同。 對於file.id
= 1,這是加入properties
表的問題。 對於file.id
= 3,我們必須加入costs
, tenants
和properties
如何編寫可以獲取我所有files
記錄的property.id
的查詢?
編輯:這將是一個示例輸出:
+---------+-------------+
| file_id | property_id |
|---------+-------------|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
+---------+-------------+
在這種情況下,所有文件都被確定為與property_id
1相關聯,但並非總是如此。
我認為沒有捷徑可走。 您需要沿着這些路線遍歷所有路徑
select -- property files
FileID, parent_id
from Files
where parent_model='property'
union
select -- property costs
FileID, c.parent_id
from
Files inner join costs C on Files.parent_id=c.id and c.parent_model='property'
where Files.parent_model='costs'
union
select -- tenant costs
FileID, t.parent_id
Files inner join costs C on Files.parent_id=c.id and c.parent_model='tenant'
inner join tenant t on t.id=c.parent_id
where Files.parent_model='costs'
.... etc.
即只是將所有變體串在一起,然后是UNION
您應該可以這樣做:
SELECT
P.id,
P.name,
P.address,
F.name,
...
FROM
Files F
LEFT OUTER JOIN Costs C ON
F.parent_model = 'Cost' AND C.id = F.parent_id
LEFT OUTER JOIN Tenants T ON
(F.parent_model = 'Tenant' AND T.id = F.parent_id) OR
(C.parent_model = 'Tenant' AND T.id = C.parent_id)
LEFT OUTER JOIN Properties P ON
(F.parent_model = 'Property' AND P.id = F.parent_id) OR
(C.parent_model = 'Property' AND P.id = C.parent_id) OR
(P.id = T.property_id)
根據您的數據,這可能會分解。 在這種情況下,我認為我不喜歡桌子設計。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.