如果结果不同,如何运行查询以从不同的表中获取数据

时间:2017-07-21 08:45:01

标签: mysql

希望有人可以帮助我从查询中获取数据

我有5张桌子

  1. 记录活动

    | id | user | activity_id | content_id |
    | 1 | 1 | 1 | 1 |
    | 2 | 1 | 2 | 1 |
    | 3 | 1 | 3 | 1 |
    | 4 | 2 | 1 | 2 |
    | 5 | 2 | 2 | 2 |
    | 6 | 2 | 3 | 2 |
    | 7 | 2 | 1 | 3 |
    | 8 | 3 | 2 | 3 |
    | 9 | 3 | 3 | 3 |
    | 10 | 3 | 1 | 1 |

  2. 2表活动     | id | name_activity |
        | 1 |查看|
        | 2 |点击按钮|
        | 3 |播放视频|

    1. 表用户 | id | name |
      | 1 |亚历克斯|
      | 2 | Andrian |
      | 3 |亚瑟|

    2. 表页面(如果activity_id = 1) | id | name |
      | 1 | HOME |
      | 2 |联系|
      | 3 |简介|

    3. 表格按钮(如果activity_id = 2) | id | name |
      | 1 |阅读更多|
      | 2 |提交|
      | 3 |注册|

    4. 如何从activity_id获取查询以显示日志活动加入到user,activity和content_id base     | id | nuser_name | activity_id | content_id |
          | 1 | Alex |查看|首页|
          | 2 | Alex |点击按钮|阅读更多|
          | 3 | Alex |播放视频| AnotherTable1 |
          | 4 | Andrian |查看|联系|
          | 5 | Andrian |点击按钮|提交|
          | 6 | Andrian |播放视频| AnotherTable2 |
          | 7 |安德里安|视图| AnotherTable3 |
          | 8 |亚瑟|点击按钮|注册|
          | 9 |亚瑟|播放视频| AnotherTable3 |
          | 10 |亚瑟|视图|主页|

      感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您可以使用LEFT JOIN,例如:

SELECT la.id, u.name, a.name_activity, IF(a.id = 1, p.name, b.name) As content_id
FROM log_activities la LEFT JOIN users u ON la.user = u.id
LEFT JOIN activity a ON la.activity_id = a.id
LEFT JOIN pages p ON la.content_id = p.id
LEFT JOIN button b ON la.content_id = b.id;