Anonymous
Anonymous

Reputation: 557

Mysql IN stopped working on 5.1

I am trying to do something in Mysql Server 5.1 on Windows.

I am positive this type of query worked in an older version of Mysql as I supplied it to a client previously without a problem.

Basically, a field in one of my tables contains several ids; such as 1,2,3,4,5

The field is of type varchar

I am trying to see if a value exists in the field by using an IN statement, like below. But it returns nothing.

What am I doing wrong? Is there a better way? Thanks.

mysql> create database testing;
Query OK, 1 row affected (0.00 sec)

mysql> use testing;
Database changed
mysql> create table table1(field1 char(20));
Query OK, 0 rows affected (0.01 sec)

mysql> create table table2(field2 char(20));
Query OK, 0 rows affected (0.00 sec)

mysql> insert into table1 values('1');
Query OK, 1 row affected (0.00 sec)

mysql> insert into table2 values('1,2,3');
Query OK, 1 row affected (0.00 sec)

mysql> select * from table1 where field1 in (select field2 from table2);
Empty set (0.00 sec)

Upvotes: 1

Views: 65

Answers (2)

Andreas Fester
Andreas Fester

Reputation: 36650

insert into table2 values('1,2,3');

most likely needs to be

insert into table2 values('1');
insert into table2 values('2');
insert into table2 values('3');

Then, your sub select select field2 from table2 returns ('1', '2', '3'), and the IN operator can be used to check if the result of the corresponding field from the main select is contained in this set.


According to the comments, the same schema seems to have worked before. I am not aware that the IN operator can be used like in the question, and splitting of column values into a row set seems to be non-trivial.

Using the FIND_IN_SET() function as proposed by @KaeL, the following query should work:

SELECT b.*
FROM table2 a
INNER JOIN table1 b ON FIND_IN_SET(b.field1, a.field2) > 0;

See also


In any case, you should consider normalizing your schema - using string lists as values of single fields can usually be much better handled by a relational database when the separate values are stored in separate rows in a separate table.

http://sqlfiddle.com/#!2/797cc/3 shows a possible solution.

Upvotes: 1

KaeL
KaeL

Reputation: 3659

From your query select * from table1 where field1 in (select field2 from table2);, what I'm imagining is like this:

Dissecting the sub-query select field2 from table2, you will have:

field2
'1,2,3'

Then the main query will be (substitution):

select * from table1 where field1 in ('1,2,3');

Obviously it will return no rows since the only value that table1.field1 has is '1'. And '1' <> '1,2,3'.

Well, I bet you are looking for this: FIND_IN_SET

Sample query:

SELECT FIND_IN_SET('1', '1,2,3'); will return 1.

Upvotes: 1

Related Questions