Tenza
Tenza

Reputation: 2401

Subquery inside IN clause

I have the following query working:

SELECT DISTINCT table1.field1, table1.field2
FROM table1
WHERE table1.field3 IN (1,2,3)

Result:

 field1 field2
 Data1  60
 Data2  61
 Data3  62

And the following query only gives me the first row when it should give the exact same result as the first query.

SELECT DISTINCT table1.field1, table1.field2
FROM table1
WHERE table1.field3 IN (SELECT table2.field1 FROM table2 WHERE table2.field2 = 100)

Result:

 field1 field2
 Data1  60

If I execute the subquery (SELECT table2.field1 FROM table2 WHERE table2.field2 = 100), the result is "1,2,3", exactly like the first query.

What i'm I missing?

Upvotes: 2

Views: 2156

Answers (1)

MatBailie
MatBailie

Reputation: 86798

What you're missing is that a string with the value '1,2,3' is not a list of three integers. It's one string.

If you want x IN (SELECT y FROM z) to behave in the same way as x IN (1,2,3), then your sub-query must return three items, with the values 1, 2, and 3.


There are Split() functions on the web that take a string and return a record set consisting of multiple integers. And that may fix your problem.

But the fact that you have a single record with a single field holding multiple values is a sign of a deeper problem. You should never store multiple values in a relational database as a single string. Instead store multiple records, or multiple fields.

Upvotes: 9

Related Questions