类别和子类别表(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与userprot_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中属于父id2
但我得到如下
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与上面的产品表有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
请告诉我缺少什么感谢
我认为这将解决您的问题。
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
您无法将递归转换为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