现有2张表
表1:用户表,字段:ID,用户名,用户积分(int)
例:1,张三,100
2,李四,20
表2:积分头衔表,字段:ID,最小积分(int),头衔名称,对应等级(int)
例:1,0,贫农,1
2,100,中农,2这2张表是没有主外键关系的问题是能不能用一句SQL查到排名前10的用户的用户名、积分、头衔、对应等级
PS:表关系说明,如上例,张三的积分是100,头衔是中农,等级2级,李四的积分是20,头衔是贫农,等级1级
表1:用户表,字段:ID,用户名,用户积分(int)
例:1,张三,100
2,李四,20
表2:积分头衔表,字段:ID,最小积分(int),头衔名称,对应等级(int)
例:1,0,贫农,1
2,100,中农,2这2张表是没有主外键关系的问题是能不能用一句SQL查到排名前10的用户的用户名、积分、头衔、对应等级
PS:表关系说明,如上例,张三的积分是100,头衔是中农,等级2级,李四的积分是20,头衔是贫农,等级1级
top 10 *
from
(select id=row_number() over(order by getdate()),* from 表1)a
join
(select id=row_number() over(order by getdate()),* from 表2)b
on
a.id=b.id
create table A(id int,username nvarchar(10),score int)
create table B(ID int,minScore int,[name] nvarchar(10),[level] int)insert into A select
1,'张三',100 union all select
2,'李四',20 insert into B select
1,0,'贫农',1 union all select
2,100,'中农',2 select A.*,
[Name]=(Select top 1 [name] from B where B.minScore<=Score order by minScore desc),
[level]=(Select top 1 [level] from B where B.minScore<=Score order by minScore desc)
from A
/*
id username score Name level
----------- ---------- ----------- ---------- -----------
1 张三 100 中农 2
2 李四 20 贫农 1(2 行受影响)*/
drop table A,B
FROM 表1
INNER JOIN 表2
ON 表1.ID = 表2.ID
ORDER BY 表1.用户积分
按照上述方法就可以实现
不过是Sql server中的方法,
其他数据库是否使用,可以查一下!
select top 10 a.用户名,a.用户积分,b.头衔名称,b.对应等级
from 表1 a left join 表2 b
on b.ID=(select top 1 ID from 表2 where a.用户积分>=最小积分 order by ID desc)
order by a.用户积分 desc
select top 10 a.用户名,a.用户积分,b.头衔名称,b.对应等级
from 表1 a left join 表2 b
on b.ID=(select top 1 ID from 表2 where a.用户积分>=最小积分 order by ID desc)
order by a.用户积分 desc
FROM 用户表 A
JOIN 积分头衔表 B
ON A.ID = B.ID
ORDER BY 用户积分 DESC
(select top 1头衔 from 积分头衔表 b where a.积分>=b.最小积分 order by 最小积分 desc ) as 头衔,
(select top 1对应等级 from 积分头衔表 b where a.积分>=b.最小积分 order by 最小积分 desc ) as 对应等级
from 用户表 a
order by 积分 desc
select *,
头衔名称=(select top 1 头衔名称 from 积分头衔表 where 最小积分<a.积分 order by 最小积分 desc),
对应等级=(select top 1 对应等级 from 积分头衔表 where 最小积分<a.积分 order by 最小积分 desc)
from 用户表 a
insert into @user
select 1,'张三',100 union all select 2,'李四',20declare @cell table(id int,mincell int,touxian varchar(100),grade int)
insert into @cell
select 1,0,'贫农',1 union all select 2,100,'中农',2select * from @user
select * from @cellselect a.*,touxian = (select top 1 touxian from @cell where a.usercell >= mincell order by mincell desc) from @user a
语句可行,等会多弄点数据测试有无BUG,先谢谢了to bancxc:
可行,也要测试有无BUG,先谢谢to shaozengwei:
仁兄没有看懂我的说明,2张表没有主外键关系,不过还是谢谢to yanglinqiang:
可行,等会测试有无BUG,先谢谢to misterliwei:
2张表没有主外键关系~ 不过还是谢谢to VincentLiang:
测试可用,等会做测试,谢谢先to cxmcxm:
语句可执行,但是没法满足我的筛选条件~谢谢
结贴~