求一条 sql 语句
大家好, 帮帮忙!!
表:TB_A
ItemID Vname Flag
1 ABC 1
2 CCC 0
3 DDD 1
4 BBB 2
5 EEE 0
表:TB_B
LID AID Lname
1 1,2 XffBee
2 2,3,4 EIKKKK
3 4,5 LLLLLL
4 2,5 BBBCCC
5 3,4,5 BEEEEE
6 2,3,5,6 EEIIII
这两个表中,要求输入一个ItemID 给 TB_A,然后找出TB_B表中 AID 存在的记录,并且还要显示TB_A 的内容,例子如下:
例如 ItemID=4,结果如下:
ItemID Vname LID Lname
4 BBB 2 EIKKKK
4 BBB 3 LLLLLL
4 BBB 5 BEEEEE
[解决办法]
declare @ItemID int
set @ItemID = 4
SELECT a.*,b.LID,b.Lname FROM TB_A AS a
INNER JOIN TB_B AS b
ON charindex( ', ' + rtrim(a.ItemID) + ', ', ', ' + b.AID + ', ') > 0
WHERE a.ItemID = @ItemID
[解决办法]
...愚钝啊,A表和B表有关系?
[解决办法]
declare @ItemID varchar(10)
set @ItemID = 4
select a.ItemID, a.Vname, b.LID, b.Lname
from
TB_A a,
(select ItemID = @ItemID, LID, Lname from TB_B where charindex(@ItemID, AID) > 0) b
where a.ItemID = b.ItemID