[英]Select form table A where value in table B
Table A 表A
id name
1 name1
2 name2
3 name3
4 name4
Table B 表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. 但是它只返回1个结果。
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 : 您可以使用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. 解决此问题的正确方法是更改表定义并使用JOIN。 For example
例如
Table A 表A
id name b_id
1 name1 1
2 name2 1
3 name3 1
4 name4 1
Table B 表B
id
1
To get names from table A that have B id 1 you would write: 要从表A中获得具有B id 1的名称,您应该编写:
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: 或者,如果您不能更改表A,则定义一个新表以维护关系AB:
Table A 表A
id name
1 name1
2 name2
3 name3
4 name4
Table B 表B
id
1
Table A_B 表A_B
a_id b_id
1 1
2 1
3 1
4 1
SQL to extract data: SQL提取数据:
select name from A join A_B on A.id = A_B.b_id where A_B.b_id = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.