有一个表food 里面有字段foodid foodname price
我想要随机取得里面的3条数据,并且这三条数据的price的综合要大于100小于200
求高手指教怎么写。
用的mysql数据库
MySQL SQL
------解决方案--------------------
。。。终于明白是啥意思了:在N多数据里,取出3个,这3个的总价在100到200,这样的“组合”就是所求,随机显示出这样的其中一个“组合”。这可以写个存储过程做个循环,比较好理解。如写一句SQL,我只想到了一个3倍笛卡尔积的查询,不过会N慢吧...
SQL:
create table food(foodid int ,foodname varchar(50),price money)
go
declare @i int
set @i=1
WHILE @i<200
begin
insert into food select @i,'foodname'+CONVERT(varchar(3),@i),@i*3
set @i=@i+1
end
go
with t as (
select t1.foodid foodid1,t1.foodname foodname1,t1.price price1
,t2.foodid foodid2,t2.foodname foodname2,t2.price price2
,t3.foodid foodid3,t3.foodname foodname3,t3.price price3
,ROW_NUMBER() over(order by NEWID()) r
from food t1,food t2,food t3
where ((t1.price+t2.price+t3.price) between 100 and 200) and (t1.foodid<>t2.foodid and t1.foodid<>t3.foodid and t2.foodid<>t3.foodid)
)
select foodid1 foodid,foodname1 foodname ,price1 price from t where t.r=1
union all
select foodid2 foodid,foodname2 foodname ,price2 price from t where t.r=1
union all
select foodid3 foodid,foodname3 foodname ,price3 price from t where t.r=1
go
drop table food
MySQL:。。。自己转化吧,不会了。