V
V
vladislav9972021-06-17 11:11:31
SQL
vladislav997, 2021-06-17 11:11:31

How to query the database correctly?

Can you tell me how to make a query in the database? There are 3 tables:
chat, group, group_chat.

And there is a request to pull all chats that belong to the same group:

SELECT c.id, c.title, c.chat_id, c.is_active
FROM chat as c
LEFT JOIN group_chat as gc
ON gc.chat_id = c.id
WHERE gc.group_id = 9

But how to make a reverse request? In the sense of pulling out just those chats that do not belong to this group?
Just changing the last line where equal to not equal does not work:
WHERE gc.group_id != 9

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-06-17
@vladislav997

SELECT *
FROM chat
WHERE NOT EXISTS ( SELECT NULL
                   FROM group_chat 
                   WHERE chat.id = chat_id
                     AND group_id = 9 )

By the way, by replacing NOT EXISTS with EXISTS, you can get the same result as in the query from the question text. With proper indexing, it will likely be even more efficient.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question