Lew wrote:
>> That's right. You want something along the lines of
>>
>> ... FROM T T1 JOIN T T2 ON T1.boss = T2.person ...
> I don't think it can be done in one SELECT query,
But the query you yourself show does it in one SELECT statement!
> SELECT t1.id AS employee_id, @boss := t2.id AS boss_id
> FROM employees AS t1 JOIN employees AS t2
> ON t1.boss = t2.id
> WHERE t1.id = @employee;
In JDBC terms, rather than PL/SQL or whatever,
SELECT t1.id AS employee_id, t2.id AS boss_id
FROM employees AS t1 JOIN employees AS t2
ON t1.boss = t2.id
WHERE t1.id = ?
> unless you assume the table to be sorted in such an order
> that bosses are come after employees, which is dangerous.
SQL tables are never in any particular order. No bugbear, no danger.
Incidentally, the use of artificial, autoincremented "id" keys in database
implementation is controversial.
- Lew
Faton Berisha - 10 Feb 2007 11:37 GMT
> > I don't think it can be done in one SELECT query,
>
[quoted text clipped - 4 lines]
> > ON t1.boss = t2.id
> > WHERE t1.id = @employee;
Not really. The way I understand it is that
the OP wants the entire hierarchical pattern,
while the query returns only the boss for a given employee.
> In JDBC terms, rather than PL/SQL or whatever,
> [snip]
It is MySQL.
> > unless you assume the table to be sorted in such an order
> > that bosses come after employees, which is dangerous.
>
> SQL tables are never in any particular order. No bugbear, no danger.
My point, exactly. Thus, you don't assume any particular order.
But, then, the query cannot select all the bosses
(i.e. the entire pattern) in a single run.
> Incidentally, the use of artificial, autoincremented "id" keys in database
> implementation is controversial.
If such an artificial order was implemented,
i.e. each boss' record coming after the corresponding employee one,
then the entire pattern could be selected
by a slightly modified version of the query,
something like
SELECT t1.id AS employee_id, @boss := t2.id AS boss_id
FROM employees AS t1 JOIN employees AS t2
ON t1.boss = t2.id
WHERE t1.id = @employee
OR (t1.id = @boss and t2.id <> t1.id);
But even in such a ("controversial") case,
the order wouldn't hold if, e.g.,
a boss and an employee switch positions,
which is reasonable enough to expect.
Hence the danger of such an assumption.
> - Lew
Faton Berisha
Lew - 10 Feb 2007 13:52 GMT
...
> SELECT t1.id AS employee_id, @boss := t2.id AS boss_id
> FROM employees AS t1 JOIN employees AS t2
[quoted text clipped - 7 lines]
> which is reasonable enough to expect.
> Hence the danger of such an assumption.
None of this has to do with Java.
- Lew