1

我有 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         |
+----+--------+---------+----------------+
4

2 回答 2

2
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
于 2013-08-23T13:24:00.970 回答
0

因为并非所有品牌都有有效的父母,所以您需要父母的左外连接:

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-23T13:29:49.000 回答