【发布时间】:2016-04-29 05:46:41
【问题描述】:
我有几个表格,一个包含主要内容的表格,以及一些使用子类创建的表格。
这个项目在 MySQL 中
父表
===========================
| id | name |
---------------------------
| 1 | website 1 |
| 2 | website 2 |
| 3 | website 3 |
===========================
child_table_1(例如烹饪网站)
=========================================================
| id | fk | url | books_for_sale |
---------------------------------------------------------
| 1 | 1 | http://foo.com | Cooking food |
| 2 | 3 | http://bar.com | Cooding bars |
=========================================================
child_table_2(例如游戏网站)
========================================================
| id | fk |url | games_for_sale |
--------------------------------------------------
| 1 | 2 |http://dad.com | Daddy Daycare |
========================================================
现在我需要将所有表中的信息合并为一个。
========================================================================
| id | fk |url | books_for_sale | games_for_sale|
------------------------------------------------------------------------
| 1 | 1 |http://foo.com | Cooking food | |
| 2 | 2 |http://dad.com | | Daddy Daycare |
| 3 | 3 |http://bar.com | Cooding bars | |
========================================================================
我试过了:
SELECT * FROM parent_table
LEFT JOIN child_table_1
ON parent_table.id = child_table_1.id
LEFT JOIN child_table_2
ON parent_table.id = child_table_2.id
还有这个:
SELECT * FROM parent_table
LEFT JOIN child_table_1
ON parent_table.id = child_table_1.id
LEFT JOIN child_table_2
ON child_table_1.id = child_table_2.id
但它们根本不起作用。
我得到的只是连接中最后一个表的内容。
在实际情况下,我需要处理大约十几个包含不同列的表。
我希望有人可以在这里帮助我。 如果有人知道在 Django 中执行此操作的好方法,那就更好了。
提前致谢。
【问题讨论】:
-
你期待什么样的结果?第三个表有 3 行?
-
@SimonHi 是的,我想要最后一张包含所有列的表格
-
结合 JOIN 和 UNION(查看我的更新)
标签: mysql django python-2.7