2015-02-23 58 views
1

我有一個表像的結構:列表子項的父視圖

+----+-----------+-----------+-----+-----------+-----------+-----+-----------+ 
| id | chld1fld1 | chld1fld2 | ... | chld1fld5 | chld2fld1 | ... | chld6fld5 | 
+----+-----------+-----------+-----+-----------+-----------+-----+-----------+ 

我改造它得到正確的父子關係。事情是,出於兼容性原因與遺留系統,我想有一個複製舊結構的觀點。我設法通過子查詢來實現:

SELECT parent.id, 
    (SELECT c.field1 FROM child c WHERE (c.parent_id = parent.id) AND (id = 1)) AS chld1fld1, 
    (SELECT c.field2 FROM child c WHERE (c.parent_id = parent.id) AND (id = 1)) AS chld1fld2, 
    ... 
    (SELECT c.field5 FROM child c WHERE (c.parent_id = parent.id) AND (id = 6)) AS chld6fld5 
FROM parent 

但是我很擔心這個操作需要的提取次數。那麼有沒有更好的方法來做到這一點?也許如果我至少可以在一個子查詢中獲取所有子字段,那已經好很多了。

回答

1

嘗試:

SELECT 
    p.id, 
    c1.field1 as chld1fld1, 
    c1.field2 as chld1fld2, 
    --etc 
    c2.field1 as chld2fld1, 
    c2.field2 as chld2fld2 
    --etc 
FROM parent p 
JOIN child c1 
    ON p.parent_id = c1.parent_id 
    AND c1.id = 1 
JOIN child c2 
    ON p.parent_id = c2.parent_id 
    AND c2.id = 2 -- Or whatever identifies this as the second child 
-- Add more joins as necessary 
相關問題