我有 3 张桌子
类型
+----+-------+ | id | type | +----+-------+ | 1 | typeA | | 2 | typeB | | 3 | typeC | +----+-------+
品牌(包含品牌和具有母品牌id的子品牌,如brandC是brandA的子品牌)
+----+--------+--------+ | id | brand | parent | +----+--------+--------+ | 1 | brandA | 0 | | 2 | brandB | 0 | | 3 | brandC | 1 | +----+--------+--------+
设备
+----+-------+-------+ | id | type | brand | +----+-------+-------+ | 1 | 1 | 2 | | 2 | 2 | 1 | | 3 | 3 | 3 | +----+-------+-------+
我写了这个查询:
$query = "select
a.id,
b.type,
c.brand
from
equipment a
join type b
on a.type=b.id
join brand c
on a.brand=c.id
where
a.id=3";
它向我显示了以下结果:
+----+--------+---------+ | id | type | brand | +----+--------+---------+ | 3 | typeC | brandC | +----+--------+---------+
如果品牌有母品牌,我该如何修改我的查询以显示母品牌。例如brandC是brandA的子品牌。所以我的结果应该是这样的:
+----+--------+---------+----------------+ | id | type | brand | Parent Brand | +----+--------+---------+----------------+ | 3 | typeC | brandC | brandA | +----+--------+---------+----------------+
当没有母品牌时,它将单元格留空
还有我将如何修改上述查询以查看所有设备及其品牌和子品牌,如下所示。
+----+--------+---------+----------------+ | id | type | brand | Parent Brand | +----+--------+---------+----------------+ | 1 | typeA | brandB | | | 2 | typeB | brandA | | | 3 | typeC | brandC | brandA | +----+--------+---------+----------------+