日期:2014-05-17  浏览次数:20679 次

两表关联不到数据
表1
id value
1 aa
2 bb
3 cc
4 dd
5 ff

表2
id pid value
1 1,2 b1
2 3 c2
3 3,4,5 d3

表1的 id对应 表2的pid 我需要查询的结果是表1的id 出现在表2的pid中就显示数据
我写的sql: select x.* from 表1 as x inner join 表2 as y on x.id in (y.pid)
只会得到 表1 id为3的数据

请问这错在哪里呀? 谢谢

------解决方案--------------------
select x.* from 表1 as x where x.id in (select y.pid from 表2 y)
------解决方案--------------------
SQL code
select x.* from 表1 as x inner join 表2 as y 
on  CHARINDEX(','+LTRIM(x.id)+',',','+y.pid+',')>0

------解决方案--------------------
select x.* from 表1 as x inner join 表2 as y on x.id in (y.pid)
这个sql比较诡异啊,不报错吗?

CHARINDEX没用过,阿汤哥搞……
------解决方案--------------------
笛卡尔积的运算错了,inner join 和 left join 以及 right join 得出的结果是不一样的。
------解决方案--------------------
探讨

SQL code
select x.* from 表1 as x inner join 表2 as y
on CHARINDEX(','+LTRIM(x.id)+',',','+y.pid+',')>0