Kristian82
Kristian82

Reputation: 1557

Using IN with a sub query

I have two tables, in one the tables there is a column that holds the ID of the other table. This column could hold more than one ID so I am storing it as a list so for instance "1,2,3,4" could be the values. So I try to use the following:

SELECT TableAValue
FROM TableA
WHERE TableAID IN 
(SELECT TableAID FROM TableB WHERE TableBID  = 1) 

This only brings back one value.

Now if I use:

SELECT TableAID FROM TableB WHERE TableBID  = 1

This brings back four values. Also if I copy those four values and use:

SELECT TableAValue
FROM TableA
WHERE TableAID IN 
(1,2,3,4) 

This will bring back the four values I am after. This seems like something very simple to do, so I guess I'm either doing it completely wrong or I'm missing some small detail. Any ideas?

Upvotes: 1

Views: 74

Answers (1)

MatBailie
MatBailie

Reputation: 86706

As mentioned in the comments discussion, your mistake is to hold four values in a single field. Doing so means that you're holding a string, a single value, not a list of integers. If you want to hold several values, you need several places to hold them individually.

So, if instead you have four records, each with a different value in TableAID, it will work exactly as you expect.

CREATE TABLE TableB (
  TableBID INT,
  TableAID INT
)

INSERT INTO TableB
      SELECT 1, 1
UNION SELECT 1, 2
UNION SELECT 1, 3
UNION SELECT 1, 4
UNION SELECT 2, 3
UNION SELECT 2, 4
UNION SELECT 2, 5
UNION SELECT 2, 6

Upvotes: 3

Related Questions