日期:2014-05-18  浏览次数:20492 次

像这样的应该怎么用sql查询呀?在线等
有两个表,一个是会员表user_info,两个字段一个是新表用户的ID(user_id),一个是原来的用户ID(y_user_id)

user_id           y_user_id

  1001                   1234
  1002                   1235
  1003                   1236
  1004                   1237

另一个表是消息表,有user_id,to_user_id两个字段,这两个ID号都是来自用户表里的y_user_id


user_id       to_user_id

1234                   1235
1236                   1237
1236                   1237
1237                   1235


现在我想要生成一个新表,将消息表的ID号都换成用户表中的user_id应该怎么查询呀?

user_id       to_user_id
  1001               1002
  1003               1004
  1003               1004
  1004               1002

刚学的sql希望大家帮帮忙,谢谢!好了,立即给分!


------解决方案--------------------
declare @a table(user_id int, y_user_id int)
insert @a select 1001, 1234
union all select 1002, 1235
union all select 1003, 1236
union all select 1004, 1237

declare @b table(user_id int,to_user_id int)
insert @b select 1234, 1235
union all select 1236 ,1237
union all select 1236 ,1237
union all select 1237 ,1235

select bb.user_id user_id,aa.user_id to_user_id from @a aa
Inner Join
(select a.user_id,to_user_id from @a a Inner Join @b b On a.y_user_id=b.user_id)
bb
on aa.y_user_id=bb.to_user_id
order by bb.user_id