Skip to content
Advertisement

Get records from table with join where records in join not contain specific value

I have two tables:

Table user:

And table address:

And some data as example:

Every user can have several addresses. I need to get all users who doesn’t have in their set of addresses address with specific country, for example ‘Germany’.

What I tried:

But it returns users, who have address with specific country but also have some other address, which country is different from the specific one, for example with the data used above this is alex, who has two addresses Germany and Great Britain:

Any suggestions how can I do such query?

Advertisement

Answer

Your code checks whether each user has at least one address outside of Germany, while you want to ensure that they have none.

I would recommend not exists:

This query would take advantage of an index on address(user_id, country).

Note that it is unclear whether your table is called user or client… I used the latter.

Note that this also returns clients that have no address at all. If that’s not what you want, then an alternative uses aggregation:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement