I want to assign one to three people to a subject. Then I want to retrieve the assignment for a particular subject.
I have one table SUBJECTS in which there is a dozen subjects (columns : id(PK), name). I have one table USERS in which there is a dozen users (columns : id(PK), firstName, lastName, etc.)
I then created a table AS_SUBJECTS in which there are the following columns (all of which are integers):
id(PK), subjectName, user1, user2, user3
Relations :
- subjectName is FK to subjects.id
- user1 is FK to users.id
- user2 is FK to users.id
- user3 is FK to users.id
I want user2 and user3 to be optional, i.e. there can be one or two or three people assigned to one subject. Therefore I have allowed NULL on these columns.
Now let's say I enter these values in AS_SUBJECTS :
id = 1
subjectName = 1
user1 = 7
user2 = NULL
user3 = NULL
If I query : SELECT * FROM as_subjects WHERE as_subjects.subjectName = 1;
I get the results for all columns, including the ones with NULL values.
The problem : I need to query a subject in AS_SUBJECTS and also retrieve users.firstName and users.lastName for each user assigned to this subject. So I use aliases :
SELECT
as_subjects.subjectName
as_subjects.user1
u1.firstName as user1FirstName
u1.lastName as user1LastName
as_subjects.user2
u2.firstName as user2FirstName
u2.lastName as user2LastName
as_subjects.user3
u3.firstName as user3FirstName
u3.lastName as user3LastName
FROM as_subjects
JOIN subjects ON as_subjects.subjectName = subjects.id
JOIN users u1 ON as_subjects.user1 = users.id
JOIN users u2 ON as_subjects.user2 = users.id
JOIN users u3 ON as_subjects.user3 = users.id
WHERE as_subjects.subjectName = 1;
The query is valid, but when as_subjects.user2 or 3 is NULL, the set in empty, no data at all.
Any inputs on how to achieve this? All I could find were posts about how to select columns where values is NULL. What I need is to select columns NO MATTER IF the value is NULL.