Cat和子类别表(cat_tbl):
id | cat_n | parent_id
1 | cat | 0
2 | dog | 0
3 | tiger | 2
4 | lion | 0
5 | abc | 0
6 | bcd | 3
现在我有一个产品表格如下(prod_tbl):
id | pwght | cid | cpid
10 | 1.2 | 1 | 0
11 | 2.4 | 2 | 0
12 | 3.4 | 2 | 0
13 | 4.5 | 6 | 3
,用户最终权重产品表格如下(userprod_tbl):
id | pwght | cid | cpid | prod_id ( is above prod_tbl primary id )
1 | 1.1 | 1 | 0 | 10
2 | 2.3 | 2 | 0 | 11
3 | 3.1 | 3 | 2 | 12
4 | 4.0 | 6 | 3 | 13
结果:(我希望输出)是prod_tbl与userprod_tbl的比较,如下所示:
Prod tbl Userprod tbl
cat 1.2 cat 1.1
dog 2.4 dog -- -- 2.3
dog 3.4 dog tiger -- 3.1
dog 4.5 dog tiger bcd 4.0
因此,在上述结果中,2.4,3.4,4.5属于父ID 2
但我得到如下
Prod tbl Userprod tbl
cat 1.2 cat 1.1
dog 2.4 dog -- -- 2.3
dog 3.4 dog tiger -- 3.1
在上面的结果中 我没有得到4.5值 ,因为4.5与上面的prod表有6,3的关系但是其id 2的父
以下是我的回复:
SELECT pt.pwght , upt.pwght ,ct.cat_n,uct.cat_n,umct.cat_n
FROM prod_tbl AS pt
LEFT JOIN userprod_tbl AS upt ON (pt.id = upt.prod_id)
LEFT JOIN cat_tbl AS ct ON pt.packet_id = ct.id
LEFT JOIN cat_tbl AS uct ON upt.packet_id = uct.id
LEFT JOIN cat_tbl AS umct ON upt.parent_packet_id = umct.id
请告诉我遗漏的内容 感谢
答案 0 :(得分:0)
这会解决我的问题。
SELECT pt.pwght AS prod_pwght, upt.pwght AS userprod_pwght ,
ct.cat_n AS prod_catName,uct.cat_n AS Userprod_catName
FROM prod_tbl AS pt
LEFT JOIN userprod_tbl AS upt ON pt.id = upt.prod_id
LEFT JOIN cat_tbl AS ct ON pt.cid = ct.id
LEFT JOIN cat_tbl AS uct ON upt.cid = uct.id;
这里有适合你的小提琴 - http://sqlfiddle.com/#!9/9568a/1
答案 1 :(得分:0)
您无法将递归转换为SQL。您可以使查询变得越来越复杂,以覆盖此递归达到确定数量的级别,但不会达到未确定的数量,并且这样做非常缓慢且完全不必要。
我建议您在脚本中获取cat_tbl
并计算此类别梯形图,而不是将其强加于MySQL。
示例(请注意我只是在没有测试的情况下写这个):
$cat_tree = [];
$res = $mysql->query('SELECT id, cat_n, parent_id FROM cat_tbl');
while ($row = $res->fetch_row())
$cat_tree[$row[0]] = [$row[1], $row[2]];
function get_tree($cid)
{
global $cat_tree;
$result = [$cat_tree[$cid][1]];
while ($cat_tree[$cid][2])
{
$cid = $cat_tree[$cid][2];
$result[] = $cat_tree[$cid][1];
}
return array_reverse($result);
}
$res = $mysql->query('SELECT pt.id, pt.cid, pt.pwght, ut.cid, ut.pwght FROM prod_tbl pt INNER JOIN userprod_tbl ut ON pt.id = u.prod_id');
while ($row = $res->fetch_row())
{
$ptree = get_tree($row[1]);
$utree = get_tree($row[3]);
printf("%s | %f | %s | %s\n", $ptree[0], $row[2], implode(', ', $utree), $row[4]);
}
这应输出如下内容:
cat | 1.2 | cat | 1.1
dog | 2.4 | dog | 2.3
dog | 3.4 | dog, tiger | 3.1
dog | 4.5 | dog, tiger, bcd | 4.0