Stewart Alan
Stewart Alan

Reputation: 1643

How can I return a list of records and true or false if a joined record exists using SQL?

I have three tables.

Table A:

TableA_ID, Description

Table B:

TableB_ID, TableA_ID, TableC_ID

Table C:

TableC_ID, Various Other columns

Table B may contain zero or more records linking a record from Table C to a record in table A

I want a query that will return ALL records from Table A and an additional column that will be True or False dependent on whether any related records exist in Table B for a specific TableC_ID value.

Any help mucho appreciated.

Cheers

Stewart

Upvotes: 1

Views: 931

Answers (1)

Joe Stefanelli
Joe Stefanelli

Reputation: 135848

SELECT a.TableA_ID, a.Description,
       CASE WHEN b.tableC_ID IS NOT NULL THEN 'True' ELSE 'False' END AS DoesExist
    FROM TableA a
        LEFT JOIN TableB b
            ON a.TableA_ID = b.TableA_ID
                AND b.TableC_ID = 123 -- Add your specific value here

Upvotes: 3

Related Questions