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

时间:2018-12-19 17:18:50

标签: php mysql

当查看并实现为表时,我有一个称为集合的MYSQL表可能是这样的:

enter image description here

我需要知道一个mysql查询是否能够在 collection 类型条目(给定)下获取所有产品,这些条目下可能有集合。例如,如果我选择10,则应返回14、12、13和15。

我实现了一个涉及do..while循环的解决方案...

$concatted = 10;
$products = [];
do {
    $sql = "SELECT id, type FROM collections WHERE parent IN ($id_concatted)";
    $result = $mysqli->query($sql);

    if($result) {
        while($row = $result->fetch_object()){
            if($row->type == 'product') {
                apply_changes_to_product($row->id);
            } elseif ($row->type=='collection'){
                $collections[] = $row->id;
            }
        }
    }
    if(count($collections) > 0){
        $id_concatted = implode($collections, ",");
        $continue = true;
        $collections = [];
    } else {
        $continue = false;
    }
} while ($continue);

我认为上面的代码效率不高。我认为使用一个查询是可行的,但我不知道如何。

更新:尽管此帖子中没有接受的解决方案,但我将其标记为How to create a MySQL hierarchical recursive query的副本。我根据那里的一个答复(Mysql 5.6)得到了这个解决方案:

SELECT id, `type` FROM (
    select  id, `type`
    from    (select * from collections
         order by parent, id) products_sorted,
        (select @pv := '10') initialisation
    where   find_in_set(parent, @pv)
    and     length(@pv := concat(@pv, ',', id))
) products
WHERE
    products.`type` = 'product'

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

1 个答案:

答案 0 :(得分:0)

是的,您可能需要使用子查询并首先获取id,其中parent = selectedId并输入类型='collection',然后在id中选择parent并在子查询ID中输入type ='product'

像下面这样:

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

对于多个级别,请使用MySql的递归功能。如下所示:

WITH RECURSIVE COLLECTIONS_PRODUCTS (ID, TYPE, PATH)
AS
(
SELECT ID, TYPE, CAST(ID AS CHAR(200))
FROM COLLECTIONS
WHERE PARENT IN ($id_concatted)
UNION ALL
SELECT S.ID, S.TYPE, CONCAT(M.PATH, ",", S.ID)
FROM COLLECTIONS_PRODUCTS M JOIN COLLECTIONS S ON M.ID=S.PARENT
)
SELECT * FROM COLLECTIONS_PRODUCTS WHERE TYPE = 'product' ORDER BY PATH;
相关问题