Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select value from table only if exist in another

Tags:

mysql

I have two tables.

Table one:

ID COLOR    
1  white 
2  red 
3  black 
4  blue 
5  yellow

Table two:

ID COLOR    
1  white 
2  white 
3  red 
4  black 

Output should be:

1 white
2 red
3 black

(exclude 2 values that don't exist in second table - blue and yellow + exclude second white).

I tried different JOIN and EXIST queries, no luck. Thanks.

like image 670
Tompo Avatar asked May 11 '15 00:05

Tompo


People also ask

How do you select all records from one table that do not exist in another table in SQL Server?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.

What to use instead of not exists?

Using Joins Instead of IN or EXISTS An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.

What does select exists return?

SQL Server EXISTS operator overview The EXISTS operator returns TRUE if the subquery returns one or more rows. In this syntax, the subquery is a SELECT statement only.


1 Answers

where exists is appropriate for this.

select * 
  from t1
  where exists 
    (select 1
      from t2 where color = t1.color);

demo here

The subquery is a correlated subquery (as it refers to a value from the other query), and as such it is executed for every row of the outer query. So all the inner query needs to do, is check and see if the colour from the outer query (and first table) is present in the second table.

like image 161
pala_ Avatar answered Oct 08 '22 19:10

pala_