这些都是假表名,但在我的实际问题中,想象一下业务规则,说明每个父代都有1或2个子代。这些孩子有0或1的数量。同一父母的两个孩子不能有相同的数字。MySQL:将另一个表中的2行合并到一个结果行中
我想要访问children
的行中的字段,但希望将值放入数字前缀字段中。例如:
parenttochildrenassoc:
+-------------+-------------+
| parent | child |
+-------------+-------------+
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
+-------------+-------------+
孩子:
+-------------+-------------+------------+
| child | number | name |
+-------------+-------------+------------+
| 1 | 0 | Chuck |
| 2 | 1 | Sally |
| 3 | 0 | Carly |
| 4 | 1 | Billy |
+-------------+-------------+------------+
期望的结果:
+-------------+-------------+------------+
| parent | child0 | child1 |
+-------------+-------------+------------+
| 1 | Chuck | Sally |
| 2 | Carly | NULL |
| 3 | NULL | Billy |
+-------------+-------------+------------+
最近我可以得到低于:
SELECT A.parent, C0.name as child0, C1.name as child1
FROM parenttochildassoc A
LEFT JOIN children C0 ON C0.child = A.child AND C0.number = 0
LEFT JOIN children C1 ON C1.child = A.child AND C1.number = 1
产生这样的:
+-------------+-------------+------------+
| parent | child0 | child1 |
+-------------+-------------+------------+
| 1 | Chuck | NULL |
| 1 | NULL | Sally |
| 2 | Carly | NULL |
| 3 | NULL | Billy |
+-------------+-------------+------------+
我如何扁平化呢?它似乎与此answer中描述的“枢轴”非常相似(其中一个建议的答案与我的尝试相同),但parenttochildrenassoc
多对一的事实似乎打破了它。
有每个单亲家庭子女的最大数目? – shmosel
1或2个孩子 – thedarklord47