I have two tables: assignment and message.
assignment
| id | message | assignor |
|---|---|---|
| 11 | 33 | 909 |
| 32 | 13 | 5464 |
| 52 | 521 | 909 |
message
| id | text | state |
|---|---|---|
| 33 | Merheba | NEW |
| 43 | Salam | READ |
| 312 | Olá | READ |
| 521 | hello | NEW |
| 412 | Hola | NEW |
| 212 | Hallo | READ |
| 765 | Saluton | READ |
assignment refers to message.
I want to query all messages where their state is 'NEW' and their assignor is 909 in assignment or they do not exist in assignment. And I need to sort the list by assignor.
I have used this query to fetch all the messages but I am not sure if is possible to sort the result.
select *
from message
where (
id not in (
select message
from assignment
)
or id in (
select message
from assignment
where assignee = 909
)
)
and state = 'NEW';
Is it possible to simplify the query? I look for the message two times.
The result must be:
| id | text | state |
|---|---|---|
| 33 | Merhaba | NEW |
| 521 | hello | NEW |
| 412 | Hola | NEW |
The first two rows have assignor (909 in assignment), and all of the three rows are 'NEW'.