求 查询语句,急急急

BeckLikeCoding 2011-02-14 10:18:45
表1:userId regIp
表2:userId userName city
表3:city startIp10 endIp10 (将regIp转成数字能与startIp10和endIp10比较,若在范围中,得出城市)

现在需求是:要查询出一个多行多列的结果集,如下形式:
userName city
数据 数据
数据 数据
数据 数据
数据 数据

若表2中city字段不为空,查出其值,若为空,则关联表1,表3查出city

这个怎么弄啊。,。忘赐教。。
...全文
115 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhongyh1024 2011-02-15
  • 打赏
  • 举报
回复
select b.username,a.city from tb3 a
left join tb2 b on a.city=b.city
left join tb1 c on b.userid=c.userid
where cast(c.regip as int) between a.startIp10 and a.endIp10
Shawn 2011-02-14
  • 打赏
  • 举报
回复
--SQL
select userName,city from tb2 where ISNULL(city, '') <> ''
union all
select b.userName, c.city from
(select userId, userName from tb2 where ISNULL(city, '') = '') b
inner join tb1 a
on a.userID = b.userId
inner join tb3 c
on c.startIp10 - CAST(a.regIp as int) <= 0 and c.endIp10 - CAST(a.regIp as int) >= 0
Shawn 2011-02-14
  • 打赏
  • 举报
回复
create table tb1
(
userID varchar(100),
regIp varchar(100)
)
insert tb1
select 'test1', '5'

create table tb2
(
userId varchar(100),
userName varchar(100),
city varchar(100)
)
insert tb2
select 'test1', 'user1', null

create table tb3
(
city varchar(100),
startIp10 int,
endIp10 int
)
insert tb3
select 'xian', 4, 10 union all
select 'guangzhou', 5, 6

--SQL
select
userName,
city = case when (ISNULL(city, '')) <> '' then city else
(select top(1) c.city from tb1 a, tb3 c
where a.userID = b.userID and c.startIp10 - CAST(a.regIp as int) <= 0 and c.endIp10 - CAST(a.regIp as int) >= 0)
end
from tb2 b
BeckLikeCoding 2011-02-14
  • 打赏
  • 举报
回复
表3是一个ip库,其中有很多IP段对应的城市,city字段有重复
快溜 2011-02-14
  • 打赏
  • 举报
回复

select b.username,a.city from tb3 a
left join tb2 b on a.city=b.city
left join tb1 c on b.userid=c.userid
where cast(c.regip as int) between a.startIp10 and a.endIp10

快溜 2011-02-14
  • 打赏
  • 举报
回复

select tb2.username,a.city from tb2 a
left join tb3 b on a.city=b.city
left join tb1 c on b.userid=c.userid
where cast(c.regip as int) between a.startIp10 and a.endIp10

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧