A表:UserID,BookNum,BookPrice,BuyTime
B表:UserID,BookNum,BookPrice
从表A读出一条数据,按A表中这条数据的条件(BookPrice相等,BookNum不小于B表中BookNum)选择B表中的数据
如果是UserID相等,则是不能购买自己的书
如果是B表中没有数据配对,则A表中跳过读下一条数据出来,再配对,再次重新读A表时,有配对则成功,没有则再跳过
如果是有符合的条件,则成功,写入当前时间,再读A表中下一条数据谢谢
B表:UserID,BookNum,BookPrice
从表A读出一条数据,按A表中这条数据的条件(BookPrice相等,BookNum不小于B表中BookNum)选择B表中的数据
如果是UserID相等,则是不能购买自己的书
如果是B表中没有数据配对,则A表中跳过读下一条数据出来,再配对,再次重新读A表时,有配对则成功,没有则再跳过
如果是有符合的条件,则成功,写入当前时间,再读A表中下一条数据谢谢
建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
1. 你的 create table xxx .. 语句
2. 你的 insert into xxx ... 语句
3. 结果是什么样,(并给以简单的算法描述)
4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。
declare @i int
set @i=1
select *,rowid=ROW_NUMBER() over(order by getdate()) into #t from A
select * into #t1 from a where 1=0
while 1=1
begin
select @UserID=UserID,@BookNum=BookNum,@BookPrice=BookPrice from A where rowid=@i
if @@ROWCOUNT=0
begin
break
end
else
begin
insert #t1
select *,GETDATE() from b where BookPrice=@BookPrice and BookNum<=@BookNum and UserID<>@UserID
end
set @i=@i+1
end
如果是UserID相等,则是不能购买自己的书这条没看懂
--游标
--未经测试,可能有语法错误
declare my_cursor cursor scroll dynamic for
select userID, bookNum, bookPrice from Adeclare @userID int, @bookNum int, @bookPrice numeric(5,2), @isFound intopen my_cursor
fetch first from my_cursor into @userID, @bookNum, @bookPricewhile(@@fetch_status = 0)
begin
select
@isFound = count(1)
from
B
where
userID <> @userID
and bookPrice = @bookPrice
and bookNum <= @bookNum
if @isFound > 0
update A
set buyTime = getdate()
where userID = @userID
and bookNum = @bookNum
and bookPrice = @bookPrice; fetch next from my_cursor into @userID, @bookNum, @bookPrice
end;fetch next from my_cursor into @userID, @bookNum, @bookPrice
close my_cursor
deallocate my_cursor--匹配更新法
--未经测试,可能有语法错误
update
a
set
buyTime = getdate()
from
A a
where
exists(select 1 from B
where userID <> a.userID
and bookPrice = a.bookPrice
and bookNum <= a.bookNum)
B表:UserID,BookNum,BookPriceselect b.* from a join b on a.bookprice=b.bookprice
where a.booknum>=b.booknum and a.userid<>b.userid