0

Table A

id    name
1     name1
2     name2
3     name3
4     name4

Table B

id    userlist
1     1,2,3,4

What I do now is

SELECT `userlist` FROM `table B` WHERE `id` = 1

Then save the result and put into second query

SELECT `name` FROM `table A` WHERE `id` in ($userlist)

Just wondering if got better way. I try

SELECT `name` FROM `table A` WHERE `id` in (SELECT `userlist` FROM `table B` WHERE `table B`.`id` = 1)

But it only return 1 result.

EDIT*

DB structure can not be change since so many data inside. I just try to optimize the old code.

  • 6
    having comma separated values in a single field of a table is generally a bad idea. You should think about your data representation. – Andreas Grapentin Feb 09 '13 at 10:37
  • Normalize your DB, then you can use `IN` or `WHERE EXISTS` – knittl Feb 09 '13 at 10:40
  • 1
    See also [Is storing a delimited list in a database column really that bad?](http://stackoverflow.com/a/3653574) – eggyal Feb 09 '13 at 10:48
  • "*DB structure can not be change since so many data inside*" - why should the amount of data in the database prevent you from altering its structure? Schema changes can be effected with database queries that perform all of the restructuring for you. – eggyal Feb 09 '13 at 10:52
  • @eggyal O,ok. But I need ensure all the new insert data can match this new DB structure right before change the DB? If not, it can cause an error. For now, I just optimize bit by bit without doing major change since I'm not totally understand the whole architecture – Muhammad Azizol Aminuddin Feb 09 '13 at 11:08

2 Answers2

3

You could use FIND_IN_SET:

SELECT `name`
FROM `table A` INNER JOIN `table B` ON
     FIND_IN_SET(`table A`.`id`, `table B`.`userlist`)
WHERE `table B`.`id` = 1

but i would suggest you to normalize your tables.

fthiella
  • 48,073
  • 15
  • 90
  • 106
2

The proper way to solve this is changing the table definition and using JOINs. For example

Table A

id    name    b_id
1     name1   1
2     name2   1
3     name3   1
4     name4   1

Table B

id    
1  

To get names from table A that have B id 1 you would write:

select name from A join B on A.b_id = B.id where B.id = 1

Or, if you can't change Table A, define a new table to maintain the relationship A-B:

Table A

id    name
1     name1
2     name2
3     name3
4     name4

Table B

id    
1     

Table A_B

a_id b_id
1    1
2    1
3    1
4    1

SQL to extract data:

select name from A join A_B on A.id = A_B.b_id where A_B.b_id = 1
Joni
  • 108,737
  • 14
  • 143
  • 193