我的表格结构如下:
+----+-----------+-----------+-----+-----------+-----------+-----+-----------+
| 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
但我担心此操作所需的提取次数。那么有更好的方法吗?也许如果我至少可以在一个子查询中获取所有子字段,那么它已经好多了。
答案 0 :(得分: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