mysql - SQL 查询从存储的表数据生成事件

标签 mysql dynamic-sql listactivity

我有三个表用于存储事件相关数据,如下所示。

Table: activity

+----+---------------+---------+
| id | activity_text | user_id |
+----+---------------+---------+
|  1 | added         |       1 |
|  2 | added         |       1 |
+----+---------------+---------+
Table: activity_modules

     +----+-------------+
     | id | module_name |
     +----+-------------+
     |  1 | posts       |
     |  2 | comments    |
     |  3 | users       |
     +----+-------------+
Table: activity_module_objects
+----+-------------+-----------+--------------+-----------+
| id | activity_id | module_id | display_text | object_id |
+----+-------------+-----------+--------------+-----------+
|  1 |           1 |         1 | new post     |        10 |
|  2 |           2 |         1 | new comment  |        11 |
|  3 |           2 |         2 | on post      |        10 |
+----+-------------+-----------+--------------+-----------+

这里的事件表代表用户和事件。 user_id 是用户表中的外键。
Activity_module_objects 中的 object_id 表示事件目标,例如 id 为 10 的帖子。这意味着帖子 10 上发生了某些操作。

我需要这样的输出,每当我使用 user_id 查询时,假设 user_id=1, {user: {id: 1, name: 'Anil'}}

阿尼尔添加了新帖子

Anil 在帖子中添加了新评论

在每个事件中,“Anil”、“评论”、“帖子”都会有链接。

Anil 喜欢 AnotherUser 的视频《野生动物》

在此事件中,Anil、AnotherUser、Wild-life 将有链接。因此,使用 user_id 我需要获取用户详细信息,使用 module_id & object_id 我需要获取对象详细信息。就像模块是“VIDEO”一样,我需要从videos表中获取video_id(来自activity_module_objects表的object_id)数据。如果是其他事件,例如事件,我需要从 events 表中获取 event_id 详细信息。

最佳答案

如果我理解正确,它将为您提供用户详细信息以及相关的 object_id 和模块名称。

SELECT u.*,
       amo.object_id,
       am.module_name
FROM USER u
LEFT JOIN activity a ON a.user_id = u.id
INNER JOIN activity_modules_object amo ON a.id = amo.activity_id
INNER JOIN activity_modules am ON am.id = amo.module_id

关于mysql - SQL 查询从存储的表数据生成事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34865557/

相关文章:

php - 如何在 cassandra CQL 中使用 like 查询?

android - Intent 项目 onClick to Activity

java - 使用 SQLite 数据库填充列表

android - 如何从 FragmentActivity 上方的 Activity 替换 Fragment

Mysql根据长度打印重复字符

mysql - 当另一个对应列为空时过滤掉某些列

sql-server - 动态 SQL 和存储过程优化

postgresql - 具有动态列名的 Postgres 选择

甲骨文创建功能

MySQL对左连接结果的限制