在不同关系上加入同一张桌子

时间:2019-04-05 07:44:27

标签: mysql sql jointable

我有3张桌子。用户,对象和项目。用户可以有许多对象,而对象可以有许多项目。此外,用户可以有许多项目。我正在为这些表做报告。

我的结果应如下:

+------------+----------------+-----------------+
| username   | Object         | Item            |
+------------+----------------+-----------------+
|  1001      | Object_name1   | Item_name1      |
|  1001      | NULL           | Item_name2      |
|  1001      | NULL           | Item_name3      |
|  1001      | NULL           | Item_name4      |
|  1001      | NULL           | Item_name5      |
|  1002      | NULL           | Item_name6      |
+------------+----------------+-----------------+
and so on..

我当前查询得到的最好的结果:

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
+------------+----------------+-----------------+-----------------+
| username   | Object         | Item            | Item_1          |
+------------+----------------+-----------------+-----------------+
|  1001      | Object_name1   | Item_name1      | Item_name2      |
|  1001      | Object_name1   | Item_name1      | Item_name3      |
|  1001      | Object_name1   | Item_name1      | Item_name4      |
|  1001      | Object_name1   | Item_name1      | Item_name5      |
|  1002      | NULL           | NULL            | Item_name6      |
+------------+----------------+-----------------+-----------------+

我的架构: enter image description here 如您所见,这是不正确的。有什么建议如何解决吗?

1 个答案:

答案 0 :(得分:0)

对于项目1,对于对象相关项目,对于用户实现的项目,您可以使用两次联接:

SELECT u.username, o.name as object, oi.name as oi_item_name, ui.name as ui_item_name
FROM users u
LEFT JOIN objects o on o.id = u.object_id 
LEFT JOIN items  oi on o.item_id  = oi.id
LEFT JOIN items ui on u.item_id  = ui.id