dongyuan9109 2016-09-10 06:25
浏览 8
已采纳

PHP Hierarchical MYSQL查询

I am trying to make a query on the database example below where if a particular ID has a parent greater than zero, echo that parent’s NAME.

For example when the query would reach ID #5, under the PARENT I would like to get “Adidas” and not “2”. Right now I get the parent’s ID, but I’d like to go a step further and retrieve the parent’s NAME.

DATABASE EXAMPLE:

ID  |  PARENT  |  NAME
———————————————————————
1   |     0    |  Nike
2   |     0    |  Adidas
3   |     1    |  Jordan
4   |     1    |  Bryant
5   |     2    |  Rose
6   |     2    |  Howard

Here is the query I am performing as it stands (it's a bit convoluted since I am calling from 2 tables):

$q = "SELECT `categories`.`ID`, `categories`.`Parent`, `categories`.`NAME`, 
             `products`.`ID` as `ID2`, `products`.`NAME` 
      FROM `categories`, `products`";

Thank you all in advance.

  • 写回答

2条回答 默认 最新

  • dtc66318 2016-09-10 06:57
    关注

    To get the desired output from the query you need to use SELF JOIN in this case as main ID and Parent ID both are in same table.

    The query will be

    SELECT `cat1`.`ID` , `cat1`.`Parent` , `cat2`.`NAME`
    FROM `categories` AS cat1
    LEFT JOIN `categories` AS cat2 ON `cat2`.`ID` = `cat1`.`PARENT` 
    

    Categories table has been joined to itself by creating aliases cat1 and cat2.

    In this case it is important that from which alias you will get name of the Parent. As ID of second alias cat2 is matched with first alias cat1, you will get the parent category name with second alias.

    Hope so it will help you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用