【发布时间】:2019-08-27 01:42:27
【问题描述】:
我有 3 张桌子。用户、对象和项目。用户可以有很多对象,对象可以有很多项。此外,用户可以拥有许多项目。我正在为这些表格做报告。
我的结果应该是这样的:
+------------+----------------+-----------------+ |用户名 |对象 |项目 | +------------+----------------+-----------------+ | 1001 |对象名称1 |项目名称1 | | 1001 |空 |项目名称2 | | 1001 |空 |物品名称3 | | 1001 |空 |物品名称4 | | 1001 |空 |物品名称5 | | 1002 |空 |物品名称6 | +------------+----------------+-----------------+ 等等..我当前查询的最佳结果:
SELECT u.username, o.name as object, i.name as item, i1.name as item_1
FROM users as u
LEFT JOIN object_user as ou on ou.user_id = u.id
LEFT JOIN objects as o on o.id = ou.object_id
LEFT JOIN object_items as oi on oi.object_id = o.id
LEFT JOIN items as i on i.id = oi.item_id
LEFT JOIN item_user as iu on iu.user_id = u.id
LEFT JOIN items as i1 on i1 = iu.item_id
+------------+----------------+-----------------+- ----------------+
|用户名 |对象 |项目 |项目_1 |
+------------+----------------+-----------------+- ----------------+
| 1001 |对象名称1 |项目名称1 |项目名称2 |
| 1001 |对象名称1 |项目名称1 |物品名称3 |
| 1001 |对象名称1 |项目名称1 |物品名称4 |
| 1001 |对象名称1 |项目名称1 |物品名称5 |
| 1002 |空 |空 |物品名称6 |
+------------+----------------+-----------------+- ----------------+
【问题讨论】:
-
我们也需要表格数据来获得结果。
-
我添加了数据库架构