I only have rudimentary SQL knowledge… This is likely simple for some of you, but nothing I have tried so far has worked.
If it’s matters this is using PostgreSQL
I’m trying to do a Select to get all the human readable IDs, from 2 related tables, where one of them is self joined, that I need to display in a listbox :
Here is the truncated Table setup (only the relevant fields)
CREATE TABLE IF NOT EXISTS UserTable(
Key0 SERIAL PRIMARY KEY,
LoginName TEXT NOT NULL);
------------------------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS Department(
Key0 SERIAL PRIMARY KEY,
ID VarChar(6) Unique NOT NULL,
Name TEXT NOT NULL,
ManagerKey Integer REFERENCES UserTable(Key0),
ReportsToKey Integer REFERENCES Department(Key0);
------------------------------------------------------------------------------------------------------------------
I am creating list for all departments
As you can see Department has a reference to itself (a Self Join) as well as to the UserTable
DeptID | Dept Name | Manager Name | ReportsToDept
The Human readable manager Name has to come from the UserTable and the ReportsTo Dept (DeptID) has to come from a different record in teh Department table.
I can get either one of the human readable fields with the the other fields i need from each Department record as shown below:
Select A.ID, A.Name As DeptName, C.loginname AS ManagerName From Department As A Left Join UserTable As C ON A.ManagerKey = C.key0
That gets me manager name…
And
Select A.ID, A.Name As DeptName, B.ID AS ReportsToDept From Department As A Left Join Department As B ON A.ReportsToKey = B.key0
Tgives me the Department ID that this one reports to.
Doing either one is pretty straightforward… but I can’t figure out how to get both in a single select!
Any help would be appreciated!
Thanks,
-karen