2013-08-23 59 views
1

我有3個表如何寫這個查詢有兩個連接

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

品牌(包括品牌和子品牌與母品牌標識,像brandC是子品牌布蘭達)

+----+--------+--------+ 
| 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是品牌A的子品牌。所以,我的結果應該是這樣的:

+----+--------+---------+----------------+ 
| id | type | brand | Parent Brand | 
+----+--------+---------+----------------+ 
| 3 | typeC | brandC | brandA   | 
+----+--------+---------+----------------+ 

,並在沒有母品牌離開細胞空白

也是我將如何修改上面的查詢,查看所有設備與他們的品牌,子品牌如下。

+----+--------+---------+----------------+ 
| id | type | brand | Parent Brand | 
+----+--------+---------+----------------+ 
| 1 | typeA | brandB |    | 
| 2 | typeB | brandA |    | 
| 3 | typeC | brandC | brandA   | 
+----+--------+---------+----------------+ 

回答

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; 

我也改變了別名是表的縮寫名。這使查詢更容易遵循。

+0

我知道在MySQL – Neal

+0

@Neal中沒有外連接。 。 。那麼你不太瞭解MySQL。它支持'left outer join'。請參閱http://dev.mysql.com/doc/refman/5.5/en/join.html。 (我在使用'left outer join'而不是'left join'方面有點過時,但MySQL也支持這一點。) –

+0

MySQL不支持的只有全外連接。 – Langdi

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