表结构大致如下:
Table_A:
A_id A_content A_others
1 xxx ……
2 xxx ……
3 xxx ……
4 xxx ……
Table_B:
B_id B_content B_others A_ids
1 …… …… 1,2
2 …… …… 1,2,3
3 …… …… 2,3
也就是说Table_B中的A_ids存放的是Table_A的ID
怎样查询出A_ids对应Table_A的记录?
select * from Table_A A where A.A_id in(1,2,3)
select B.A_ids from Table_B B where B.B_id = 2 --输出为:1,2,3 select * from Table_A A where A.A_id in(select B.A_ids from Table_B B where B.B_id)
这样写是不行的!奇怪!
Table_A:
A_id A_content A_others
1 xxx ……
2 xxx ……
3 xxx ……
4 xxx ……
Table_B:
B_id B_content B_others A_ids
1 …… …… 1,2
2 …… …… 1,2,3
3 …… …… 2,3
也就是说Table_B中的A_ids存放的是Table_A的ID
怎样查询出A_ids对应Table_A的记录?
select * from Table_A A where A.A_id in(1,2,3)
select B.A_ids from Table_B B where B.B_id = 2 --输出为:1,2,3 select * from Table_A A where A.A_id in(select B.A_ids from Table_B B where B.B_id)
这样写是不行的!奇怪!
先用sql把值为“1,2,3”拆分变成
1
2
3
这样的形式,然后再进行表连接就行。关于值拆分的SQL可以参考下面的帖子:
http://topic.csdn.net/u/20080721/12/c87d1a1d-b817-4de6-84ac-4f6ab56ef15a.html
如果想写存储过程实现的话,参考下面的帖子:
http://topic.csdn.net/u/20080905/19/130f6bc8-6885-473f-bd5d-e6688cb0ad8b.htmlGood luck to you!
where B.B_id = 2 and b.a_ids like '%'||a.a_id||'%'
where instr(','||b.a_ids||',',','||A.A_id||',')>0 and B.B_id=2
select a.* from Table_A A,Table_B B
where B.B_id = 2 and ','||b.a_ids||',' like '%'||','||a.a_id||','||'%'