dpaal28266 2016-11-25 08:23
浏览 165
已采纳

mysql层次递归查询

I’ve been building PHP web pages for quite a while now, but I am not really familiar with MySQL databases. I have thoroughly searched for solutions to problems like mine but without any luck (though there were similar questions answered, I could not figure out how to implement the solution provided).

I have 5 tables in a 3-level hierarchical structure as follows:

Clients (id, name, ...)
 ↳ Projects (id, client_id, name, ...)
   ↳ Contacts (id, project_id, name, ...)
   ↳ Files (id, project_id, name, ...)
   ↳ Events (id, project_id, name, ...)

I am trying to achieve a recursive query with a twist: if I provide an ID of any level (with specifying the level that ID belongs to), it should return that levels both parent and child records in a tree-structure.

For example : I have a Project’s ID, so I would like to return the Client (parent) that Project belongs to, and also the Project’s Contacts, Files, and Events (children). Or if I have an Event’s ID, then I would like to output the Project (parent), the Client (parent parent), plus Contacts and Files (which are on the same level as Events).

The point would be to see a selected item's full history. Is this even possible with one query...? Any suggestions are welcome and appreciated!

  • 写回答

1条回答 默认 最新

  • donglu9825 2016-11-25 08:41
    关注

    A query like this will return the entire data set:

    SELECT columns
         , I
         , actually
         , want
       FROM clients c
      LEFT
      JOIN projects p
        ON p.fk = c.pk
      LEFT 
      JOIN 
         ( SELECT 'contact' type, common, columns FROM contacts
            UNION
           SELECT 'file', etc
           UNION etc
         ) x
        ON x.fk = p.pk;
    

    You can easily attach a WHERE clause to this or, if the data set is not so large, just handle the filtering in JavaScript or similar. Note that your current design has potential for tremendous redundancy!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示