Reputation: 7217
I have a table in my database I do a Select all on:
SELECT * FROM TableA;
I want to append a column that is true or false if there's a related column in anther table. I can do it with this:
SELECT *, (SELECT COUNT(Id) > 0 FROM TableB WHERE Id = TableA.Id) FROM TableA;
But I don't want to have to count EVERY row in TableB to work this out as its ineffient. I essentially want an EXISTS
check instead of count.
How do I replace the COUNT
with EXISTS
?
Thanks!
Upvotes: 0
Views: 104
Reputation: 7217
Ah - just realised the answer to my own question
SELECT *, EXISTS(SELECT Id FROM TableB WHERE Id= TableA.Id) AS DoesExist FROM TableA
Upvotes: 1
Reputation: 204766
By using a left join
SELECT a.*, b.id is not null as condition_check
FROM TableA a
LEFT JOIN TableB b ON a.Id = b.Id
Upvotes: 1