Reputation: 623
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.
Upvotes: 0
Views: 1609
Reputation: 111259
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
Upvotes: 2
Reputation: 49049
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.
Upvotes: 3