【发布时间】:2015-06-12 12:45:52
【问题描述】:
我有以下表格和样本数据:
Table: activities
+------------------+---------------+
| activity_id (PK) | activity_name |
+------------------+---------------+
| 18 | Bicycling |
| 19 | Running |
+------------------+---------------+
Table: activity_attributes
+------------------+-------------------+
| activity_id (FK) | attribute_id (FK) |
+------------------+-------------------+
| 18 | 55 |
| 18 | 56 |
| 18 | 57 |
| 19 | 56 |
+------------------+-------------------+
Table: attributes
+-------------------+----------------+
| attribute_id (PK) | attribute_name |
+-------------------+----------------+
| 55 | City |
| 56 | Duration |
| 57 | Bike |
+-------------------+----------------+
Table: attributes_options
+-------------------+---------------+
| attribute_id (FK) | option_id(FK) |
+-------------------+---------------+
| 55 | 56 |
| 55 | 57 |
| 57 | 58 |
| 57 | 59 |
| 57 | 60 |
| 57 | 61 |
+-------------------+---------------+
Table: options
+----------------+---------------+
| option_id (PK) | option_name |
+----------------+---------------+
| 56 | Stockholm |
| 57 | Vasteras |
| 58 | My own |
| 59 | Rented bike |
| 60 | Borrowed bike |
| 61 | My old bike |
+----------------+---------------+
目前我的查询如下所示:
SELECT *
FROM activities a
LEFT JOIN activity_attributes aa ON a.activity_id = aa.activity_id
LEFT JOIN attributes at ON aa.attribute_id = at.attribute_id
LEFT JOIN attributes_options ao ON at.attribute_id = ao.attribute_id
LEFT JOIN options o ON ao.option_id = o.option_id
但是,对于没有任何相应选项的属性(在本例中为“持续时间”),它会返回空属性 ID。我尝试了不同的连接,但最终这个查询返回了最准确的数据,但仍然不是我要查找的所有数据。
这是我第一次使用关系数据库,我正在努力解决这个问题,我该怎么做才能为这些示例返回正确的 56 属性 ID?
【问题讨论】:
-
您的查询应该返回所有活动以及相关的属性和选项。你确定你没有
WHERE子句吗? -
嗨@GordonLinoff,是的,我没有 WHERE 子句。这是作为 JSON 数组 pastebin.com/G1eEzbb6 的返回对象的粘贴
-
使用您提供的数据,您的预期结果是什么?
-
@McAdam331 我的预期结果是pastebin.com/rNEvd2z5,而不是上述粘贴中的实际结果。
-
我现在明白了。我已经给出了答案,希望清楚。
标签: mysql database join relational-database jointable