7 ms·
If I was going to do something like this, I would adopt adopt a referencing table scoped name for the referenced table for each foreign key, and then just let y
by dragonwriter 5y ago
If I was going to do something like this, I would adopt adopt a referencing table scoped name for the referenced table for each foreign key, and then just let you refer to that in the from clause of the query to specify a join on that foreign key relationship.
So, for example, you would have the DDL:
CREATE TABLE staff (
id serial primary key,
name varchar not null,
manager_id references employees (id) as manager,
);
Then you could do:
SELECT staff.name, manager.name
FROM staff
INNER JOIN staff->manager as manager
Which would be equivalent to:
SELECT employee.name, manager.name
FROM staff as employee
INNER JOIN staff as manager on (
employee.manager_id = manager.id
)
Maybe even allow using the table->relationship name in the SELECT (or WHERE) clause for an implicit inner join, so you could just do this for the above:
SELECT staff.name, staff->manager.name
FROM staff
Or this to get a list of staff by manager name:
SELECT staff.*
FROM staff
WHERE staff->manager.name = "John Smith"
Of course, if you are doing that, maybe adopt a syntax for implicit outer joins, too, then you can get a list of employees with no subordinates with:
SELECT staff*->manager.*
FROM staff
WHERE staff.id IS NULL
Which would be equivalent to:
SELECT manager.*
FROM staff AS employee
RIGHT OUTER JOIN staff AS manager ON (
employee.manager_id = manager.id
)
- JoelJacobson 5y agoI think these are all interesting ideas! I also think making changes to the SELECT clause of the SQL language could be more difficult though. You also have to think about what type of join something like "SELECT staff->manager.name" would cause under the hood, would it be a LEFT JOIN or an INNER JOIN?