Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server SELECT Where Value Equals Results of Another Select

I want to create a SQL statement to select values from one table based on the values from another. I would like to know how to do so in SQL, but knowing in PostgreSQL would be nice as well.

EX:

TableA
ID | Label | Value
1    Test    A


TableB
ID | Name | Label
1    TestN  Test

I think the query would looks something like this:

SELECT Name FROM TableB WHERE Label = SELECT Label FROM TableA WHERE Value = 'A';

That one throws errors though. Thoughts?

like image 802
Soatl Avatar asked Dec 10 '13 22:12

Soatl


3 Answers

You're close... try this:

SELECT Name FROM TableB WHERE Label IN ( SELECT Label FROM TableA WHERE Value = 'A' );

EDIT: Started to add the INNER JOIN option but it is listed in another answer below.

like image 71
Matt Welch Avatar answered Nov 04 '22 01:11

Matt Welch


Why don't you do a INNER JOIN?

SELECT DISTINCT B.Name
FROM TableB B
INNER JOIN TableA A ON B.Label = A.Label
WHERE A.Value = 'A'
like image 43
Radu Gheorghiu Avatar answered Nov 04 '22 01:11

Radu Gheorghiu


use IN not equals:

select Name
from TableB
where Label in ( SELECT Label FROM TableA WHERE Value = 'A' );
like image 40
John Gibb Avatar answered Nov 03 '22 23:11

John Gibb