Friday, 23 August 2013

How to write this query with two joins

How to write this query with two joins

I have 3 table
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 | 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. 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 |
+----+--------+---------+----------------+

No comments:

Post a Comment