[英]How to write this query with two joins
I have 3 table 我有3张桌子
type 类型
+----+-------+ | id | type | +----+-------+ | 1 | typeA | | 2 | typeB | | 3 | typeC | +----+-------+
brand (contains brands and sub brands with parent brand id, like brandC is a sub brand of brandA) 品牌(包含具有父品牌ID的品牌和子品牌,例如brandC是brandA的子品牌)
+----+--------+--------+ | id | brand | parent | +----+--------+--------+ | 1 | brandA | 0 | | 2 | brandB | 0 | | 3 | brandC | 1 | +----+--------+--------+
equipment 设备
+----+-------+-------+ | id | type | brand | +----+-------+-------+ | 1 | 1 | 2 | | 2 | 2 | 1 | | 3 | 3 | 3 | +----+-------+-------+
I wrote this query: 我写了这个查询:
$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";
it shows me the result below: 它向我显示以下结果:
+----+--------+---------+ | id | type | brand | +----+--------+---------+ | 3 | typeC | brandC | +----+--------+---------+
How shall I modify my query to show the parent brand as well if a brand has a parent brand. 如果一个品牌有一个母品牌,我该如何修改查询以显示母品牌。 for instance brandC is a sub brand of brandA.
例如brandC是brandA的子品牌。 So my result should look like:
所以我的结果应该像这样:
+----+--------+---------+----------------+ | id | type | brand | Parent Brand | +----+--------+---------+----------------+ | 3 | typeC | brandC | brandA | +----+--------+---------+----------------+
and when there is no parent brand it leaves the cell blank 当没有父品牌时,它将单元格留空
also How will I modify the above query to see all equipment with their brands and sub brands like below. 另外,我将如何修改上面的查询以查看具有其品牌和子品牌的所有设备,如下所示。
+----+--------+---------+----------------+ | id | type | brand | Parent Brand | +----+--------+---------+----------------+ | 1 | typeA | brandB | | | 2 | typeB | brandA | | | 3 | typeC | brandC | brandA | +----+--------+---------+----------------+
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 brand
Because not all brands have valid parents, you need a left outer join for the parent: 因为并非所有品牌都有有效的父代,所以您需要为父代添加左外部联接:
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;
I also changed the aliases to be abbreviations of the table names. 我还更改了别名,使其成为表名的缩写。 This makes the query much easier to follow.
这使查询更容易遵循。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.