【发布时间】:2016-07-14 04:25:54
【问题描述】:
我有以下事件表。
活动
+---------+---------------+
| column | type |
+---------+---------------+
| id | int(11) |
| title | varchar(255) |
| content | longtext |
+---------+---------------+
event_attachment
+----------+---------------------------------+
| column | type |
+----------+---------------------------------+
| id | int(11) |
| caption | varchar(255) |
| type | enum('AUDIO', 'VIDEO', 'IMAGE') |
| path | varchar(255) |
| position | int(11) |
+----------+---------------------------------+
event_gallery
+---------------+---------+
| column | type |
+---------------+---------+
| event_id | int(11) |
| attachment_id | int(11) |
+---------------+---------+
我可以从单独的查询中获取事件附件,例如 -
SELECT ea.id, ea.caption, ea.type, ea.path, ea.position
FROM `event_attachment` ea
WHERE ea.id
IN (SELECT eg.attachment_id FROM `event_gallery` eg WHERE eg.event_id = {$event_id})
ORDER BY ea.position ASC;
但我不能直接对event_attachment 和events 执行JOIN。
我也可以得到event,它是单个附件 -
SELECT e.title , eg.attachment_id
FROM `events` e
JOIN `event_gallery` eg
ON e.id = eg.event_id
GROUP BY e.id
我无法让上述两个查询一起工作,并在单个查询中提供整个事件详细信息及其附件。
我想要的是在每个事件的第一个位置获取事件列表以及事件附件。现在,一个事件可能会或可能不会附加。
期望的输出 -
+----+-------------------+-------------------------------------------------------+------------------------------------------+----------+--+
| id | title | content | path | position | |
+----+-------------------+-------------------------------------------------------+------------------------------------------+----------+--+
| 1 | Barclay Delacruz | Soluta minim eiusmod laborum minima cumque fugiat | e2d80cd9-7e4f-4a3d-92b5-d5c600367499.jpg | 1 | |
| 2 | Lesley Strickland | Rem culpa dolor doloremque modi nisi esse exercita... | 2b15b00f-f094-469b-a56f-de7460326110.jpg | 1 | |
+----+-------------------+-------------------------------------------------------+------------------------------------------+----------+--+
注意问题可能听起来重复,因为英语不是我的第一语言,而且很难将整个场景放在一个问题中。
【问题讨论】:
-
"我不能直接在 event_attachment 和 events 上执行 JOIN" ??为什么不呢?
-
@Strawberry 我正在创建 sqlfiddle。稍后将使用链接更新问题
-
@Strawberry 我添加了带有示例数据和查询的 sqlfiddle。请看一看。
-
@Strawberry 请查看更新。
标签: mysql sql database join database-design