获取给定集合下的所有产品

xwbd5t1u  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(392)

这个问题在这里已经有答案了

如何创建mysql分层递归查询(15个答案)
两年前关门了。
我有一个名为collections的mysql表,当作为一个表来查看和实现时,可以是这样的:

我需要知道一个mysql查询是否能够获得一个集合类型项(给定项)下的所有产品,该项下可能有集合。例如,如果我选择10,它应该返回14、12、13和15。
我实现了一个涉及do..while循环的解决方案。。。

  1. $concatted = 10;
  2. $products = [];
  3. do {
  4. $sql = "SELECT id, type FROM collections WHERE parent IN ($id_concatted)";
  5. $result = $mysqli->query($sql);
  6. if($result) {
  7. while($row = $result->fetch_object()){
  8. if($row->type == 'product') {
  9. apply_changes_to_product($row->id);
  10. } elseif ($row->type=='collection'){
  11. $collections[] = $row->id;
  12. }
  13. }
  14. }
  15. if(count($collections) > 0){
  16. $id_concatted = implode($collections, ",");
  17. $continue = true;
  18. $collections = [];
  19. } else {
  20. $continue = false;
  21. }
  22. } while ($continue);

我认为上面的代码效率不高。我认为这是可行的一个问题,但我不知道如何。
更新:我将此标记为如何创建mysql分层递归查询的副本,尽管在那篇文章中没有可接受的解决方案。我得到这个解决方案是基于一个回复(mysql 5.6):

  1. SELECT id, `type` FROM (
  2. select id, `type`
  3. from (select * from collections
  4. order by parent, id) products_sorted,
  5. (select @pv := '10') initialisation
  6. where find_in_set(parent, @pv)
  7. and length(@pv := concat(@pv, ',', id))
  8. ) products
  9. WHERE
  10. products.`type` = 'product'

小提琴是http://sqlfiddle.com/#!9/ea214f/2。

whitzsjs

whitzsjs1#

是的,您可能需要使用子查询并首先获取id,其中parent=selectedid,type=collection,然后选择id,其中parent在子查询id和type=product中
如下所示:

  1. SELECT id, type FROM collections WHERE parent IN (select id from collections where
  2. parent = $id_concatted and type = 'collection') and type = 'product'

对于多层,使用mysql的递归特性。如下所示:

  1. WITH RECURSIVE COLLECTIONS_PRODUCTS (ID, TYPE, PATH)
  2. AS
  3. (
  4. SELECT ID, TYPE, CAST(ID AS CHAR(200))
  5. FROM COLLECTIONS
  6. WHERE PARENT IN ($id_concatted)
  7. UNION ALL
  8. SELECT S.ID, S.TYPE, CONCAT(M.PATH, ",", S.ID)
  9. FROM COLLECTIONS_PRODUCTS M JOIN COLLECTIONS S ON M.ID=S.PARENT
  10. )
  11. SELECT * FROM COLLECTIONS_PRODUCTS WHERE TYPE = 'product' ORDER BY PATH;
展开查看全部

相关问题