如何使用两个连接编写此查询

时间:2013-08-23 13:20:47

标签: php mysql

我有3张桌子

    +----+-------+
    | id | type  |
    +----+-------+
    |  1 | typeA |
    |  2 | typeB |
    |  3 | typeC |
    +----+-------+

品牌(包含品牌和子品牌与母品牌ID,如brandC是品牌A的子品牌)

+----+--------+--------+
| 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         |
+----+--------+---------+----------------+

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

我还将别名更改为表名的缩写。这使得查询更容易理解。