SQL多表查询
下面有3个表
----------------------------------------------------------------------------------------------
A表
id zj fb
1 1 b,id,1
2 1 c,id,1
3 1 b,id,2
4 2 b,id,3
5 3 c,id,2
B表
id remark
1 aa
2 bb
3 cc
C表
id content
1 aa
2 dd
----------------------------------------------------------------------------------------------
现在要查询zj为1,模糊查询内容为aa的记录。
如结果:id zj fb 内容id 内容
1 1 b,id,1 1 aa
2 1 c,id,1 1 aa
------解决方案--------------------select a.* ,ISNULL(b.id,c.id)内容id,ISNULL(b.remark,c.content) 内容
from [A] a
LEFT JOIN [b] ON REVERSE(SUBSTRING(REVERSE(a.fb),1,PATINDEX('%,%',REVERSE(fb))-1))=b.id AND SUBSTRING(a.fb,0,PATINDEX('%,%',a.fb))='B'
LEFT JOIN [C] ON REVERSE(SUBSTRING(REVERSE(a.fb),1,PATINDEX('%,%',REVERSE(fb))-1))=c.id AND SUBSTRING(a.fb,0,PATINDEX('%,%',a.fb))='c'
WHERE a.zj=1 AND (c.CONTENT LIKE '%aa%' OR b.remark LIKE '%aa%')
你把表名和列名改一下试试