我有三张桌子
类型
+----+-------+ | id | type | +----+-------+ | 1 | typeA | | 2 | typeB | | 3 | typeC | +----+-------+
品牌(包括带有父品牌id的品牌和子品牌,如brandC是brandA的子品牌)
+
设备
+
我写了这个查询:
$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";它向我展示了以下结果:
+--+--+
我应该如何修改我的查询,以显示父品牌以及如果一个品牌有一个父品牌。例如,brandC是brandA的一个子品牌。所以我的结果应该是:
+--+
当没有父品牌时,它将单元格保留为空白。
此外,我将如何修改上述查询,以查看所有的设备与他们的品牌和子品牌如下。
+--+--+++
发布于 2013-08-23 13:29:49
因为并不是所有品牌都有有效的父母,所以您需要为父母提供一个左外部连接:
select e.id, t.type, b.brand, bp.brand as parentBrand
from equipment e join
type t
on e.type= t.id join
brand b
on e.brand = b.id left outer join
brand bp
on b.parent = bp.id
where e.id = 3;我还将别名更改为表名的缩写。这使得查询更容易理解。
发布于 2013-08-23 13:24:00
SELECT * FROM brands b
JOIN equipment e on e.brand = b.id -- match type to brand
JOIN types t on t.id = e.type -- get type names
JOIN brands p on p.id = b.parent; -- get parent brandhttps://stackoverflow.com/questions/18403931
复制相似问题