我正在尝试加入两个表(父级和子级),但我只希望为每个父级返回一个子级...
select parent.name,child.name from parent left join child on parent.id=child.parentid
对于上述内容,将返回每个子项并复制父项。我不会为哪个孩子归来感到困扰。
感谢您的帮助
克里斯
答案 0 :(得分:2)
只是@Mahesh Madushanka的样本。我稍后会将其删除,但我无法在评论中对其进行格式化
这里是我的2张桌子
MariaDB [yourSchema]> select id from table1;
+--------+
| id |
+--------+
| 000001 |
| 000002 |
| 000003 |
| 000004 |
| 000005 |
| 000005 |
+--------+
6 rows in set (0.00 sec)
MariaDB [yourSchema]> select id from table2;
+--------+
| id |
+--------+
| 000001 |
| 000001 |
| 000002 |
| 000002 |
| 000003 |
| 000004 |
+--------+
6 rows in set (0.00 sec)
只有加入
的结果MariaDB [yourSchema]> SELECT t1.id,t2.id FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id;
+--------+--------+
| id | id |
+--------+--------+
| 000001 | 000001 |
| 000001 | 000001 |
| 000002 | 000002 |
| 000002 | 000002 |
| 000003 | 000003 |
| 000004 | 000004 |
| 000005 | NULL |
| 000005 | NULL |
+--------+--------+
8 rows in set (0.01 sec)
结果加入并分组 - t1.id = 1和2错过1次
MariaDB [yourSchema]> SELECT t1.id,t2.id FROM table1 t1
-> LEFT JOIN table2 t2 ON t1.id = t2.id
-> GROUP BY t2.id;
+--------+--------+
| id | id |
+--------+--------+
| 000005 | NULL |
| 000001 | 000001 |
| 000002 | 000002 |
| 000003 | 000003 |
| 000004 | 000004 |
+--------+--------+
5 rows in set (0.00 sec)
答案 1 :(得分:0)
从parent.id选择parent.name,child.name从parent.id = child.parentid group by parent.id