简体   繁体   中英

Select form table A where value in table B

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.

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.

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 AB:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM