Using PostgreSQL 9.2.4, I have a table users
with a 1:many relation to the table user_roles
. The users
table stores both employees and
New Answer:
This( SQL Sub queries in check constraint ) seems to answer your question, and the language is still in the 9.4 documentation( http://www.postgresql.org/docs/9.4/interactive/sql-createtable.html ).
Old Answer:
SELECT
User.*
, UserRole1.*
FROM
User
LEFT JOIN UserRole UserRole1
ON User.id = UserRole1.UserId
AND (
(
User.employee_number IS NOT NULL AND UserRole1.role_name IN (enumerate employee role names here)
)
OR
(User.employee_number IS NULL)
)
The above query selects all fields from User
and all fields from UserRole
(aliased as UserRole1). I assumed that the key field between the two fields is known as User.id and UserRole1.UserId
, please change these to whatever the real values are.
In the JOIN
part of the query there is an OR that on the left side requires an employee number not be NULL
in the user table and that UserRole1.role_name be in a list that you must supply to the IN ()
operator.
The right part of the JOIN
is the opposite, it requires that User.employee_number
be NULL
(this should be your non-employee set).
If you require a more exact solution then please provide more details on your table structures and what roles must be selected for employees.