Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql join which tells me if ID exists in other table

Tags:

sql

join

I have 2 tables:

 A      B
 --    ----
 ID    FKID
 --    ----
 1      3
 2      3   
 3      4
 4      4

I need a select statement which shows me all of A with a field that tells me if table B has any ids that match that ID.

Desired Result
-----------
 ID | hasB
-----------
 1    no
 2    no    
 3    yes
 4    yes
like image 548
capdragon Avatar asked Dec 07 '11 16:12

capdragon


People also ask

How do you check if a column exists in another table SQL?

For checking the existence we need to use the COL_LENGTH() function. COL_LENGTH() function returns the defined length of a column in bytes. This function can be used with the IF ELSE condition to check if the column exists or not.

Which join will be used to find out matched and unmatched values from two tables?

Outer joins are joins that return matched values and unmatched values from either or both tables.

What type of join only returns values when a match is found in both tables?

When you use a simple (INNER) JOIN , you'll only get the rows that have matches in both tables. The query will not return unmatched rows in any shape or form.


2 Answers

In SQL Server this would be the most efficient way rather than doing an OUTER JOIN then removing the duplicates with DISTINCT. Not sure for postgres, you'd need to check the plans.

SELECT ID,
       CASE
         WHEN EXISTS (SELECT *
                      FROM   B
                      WHERE  B.FKID = A.ID) THEN 'yes'
         ELSE 'no'
       END AS hasB
FROM   A  
like image 194
Martin Smith Avatar answered Sep 18 '22 12:09

Martin Smith


SELECT DISTINCT
    a.ID,
    CASE WHEN b.FKID IS NULL THEN 'no' ELSE 'yes' END AS hasB
FROM
    tableA a LEFT JOIN
    tableB b ON a.ID = b.FKID
like image 32
Michael Fredrickson Avatar answered Sep 21 '22 12:09

Michael Fredrickson