Hi @zoe Ohara ,
Generally, if you want to return records that do not exist in another table,please try:
SELECT UserGroupId
FROM usergroup
WHERE code = 'AAA' and usergroupid not in (select usergroupid from usergroupaccount)
But I see that you want to return the records of two tables, and according to your code, it seems that the first table is related to the second table, and the second table is related to the third table.If follow your join method, you will not be able to return records that do not exist in the second table, because join will return the data that meets the on condition in the second table.If the first table and the third table are also related, then the problem is easy:
SELECT ug.UserGroupId, a.sAccountCode
FROM usergroup ug
JOIN dbo.tblAccount a
ON ug.XXX = a.XXX
WHERE ug.code = 'AAA' and usergroupid not in (select usergroupid from usergroupaccount)
If the first table and the third table are not related, then the records that do not exist in the second table, there will be no relevant information in the third table, you only need to follow the first method to return the results you expect:
SELECT UserGroupId
FROM usergroup
WHERE code = 'AAA' and usergroupid not in (select usergroupid from usergroupaccount)
Exists and in have similar functions,for more details, please refer to:EXISTS (Transact-SQL) and IN (Transact-SQL)
If you have any question, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.
Best Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.