mySQL query for selecting children

前端 未结 7 917
失恋的感觉
失恋的感觉 2020-12-20 05:59

I am not sure if this is possible in mySQL. Here are my tables:-

Categories table:

  • id
  • name
  • parent_id (which points to Categories.id)<
7条回答
  •  时光说笑
    2020-12-20 06:34

    Bear with me, because I have never done something like this.

    BEGIN
      SET cat = "5";
      SET temp = "";
    
      WHILE STRCMP(temp, cat) != 0 DO
        SET temp = cat;
        SET cat = SELECT CONCAT_WS(GROUP_CONCAT(id), cat) FROM Categories GROUP BY (parent_id) HAVING FIND_IN_SET(parent_id, cat);
      END LOOP;
    END;
    
    SELECT * FROM products WHERE FIND_IN_SET(category_id, cat)
    

    I can almost guarantee the above won't work, but you can see what I'm trying to do. I got this far and I just decided to not finish the end of the query (select the top N from each category), sorry. :P

提交回复
热议问题