怎么样根据A表主键集 关联B表数据

MySql 码拜 8年前 (2016-02-16) 912次浏览
A表如下
id             B_ids
148 1,2,3
151 2
152 3
153 0
B表如下
id             name
1 四段7-47号
2 三段22-22号
3 四段6-133号
4 三段22-19号
5 二段24-109号
问题:B_ids是B表中主键集,怎么样根据A表中B_ids集  关联  B表中ID,从而显示B表的name
例如上便2表就显示出来
id             name
1 四段7-47号
2 三段22-22号
3 四段6-133号
2 三段22-22号
3 四段6-133号
解决方案

10

try this:

mysql> use world;
Database changed
mysql> create table A(id int,B_ids varchar(30));
Query OK, 0 rows affected (0.31 sec)
mysql> insert into A values(148,"1,2,3"),(151,"2"),(152,"3"),(153,"0");
Query OK, 4 rows affected (0.05 sec)
Records: 4  Duplicates: 0  Warnings: 0
mysql> create table B(id int,name varchar(50));
Query OK, 0 rows affected (0.40 sec)
mysql> insert into B values(1, "四段7-47号"),(2,"三段22-22号"),(3,"四段6-133号"),(4,"三段22-19号"),(5, "二段24-109号");
Query OK, 5 rows affected (0.07 sec)
Records: 5  Duplicates: 0  Warnings: 0
mysql> select B.*  from A , B  where concat(",",A.B_ids,",") like concat("%,",cast(B.id as char),",%") order by A.id,B.id;
+--+--+
| id   | name        |
+--+--+
|    1 | 四段7-47号  |
|    2 | 三段22-22号 |
|    3 | 四段6-133号 |
|    2 | 三段22-22号 |
|    3 | 四段6-133号 |
+--+--+
5 rows in set (0.00 sec)
mysql>

10

select a.id,b.id,b.name
from a,b
where FIND_IN_SET(b.id,a.B_ids)
order by a.id,b.id;

10

select a.id,b.id,b.name
from a,b
where FIND_IN_SET(b.id,a.B_ids)
order by a.id,b.id;
这个好用,但是只能索引走的不好,A表的B_IDS为什么用逗号这样方式存储,不好,用多条记录存储不好嘛
A表如下
id             B_ids
148  1
148  2
148  3
151  2
152  3
153  0

10

假如A表的B_IDS想显示成一条,可以用GROUP_CONCAT(B_IDS)也是逗号分隔转成一条的,B_IDS改为INT型,索引走的也好的

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎么样根据A表主键集 关联B表数据
喜欢 (0)
[1034331897@qq.com]
分享 (0)