0

I have a table

--------------------
ID | Name | RollNO
--------------------
1  | A    | 18
--------------------
2  | B    | 19RMK2
--------------------
3  | C    | 20
--------------------

My second table is

-----------------------
OldRollNo | NewRollNo
-----------------------
18        |  18RMK1
-----------------------
19        |  19RMK2
-----------------------
20        |  20RMK3
-----------------------
21        |  21RMK4
-----------------------
22        |  22RMK5
-----------------------

I want the resulting table like

----------------------------------
ID | Name | RollNo | LatestRollNo
----------------------------------
1  | A    | 18     | 18RMK1
----------------------------------
2  | B    | 19RMK2 | 19RMK2
----------------------------------
3  | C    | 20     | 20RMK3
----------------------------------

What would be the select query like? This is just the replica of my problem. I have used CASE Statement with the select query but as the records in my table is large, it's taking too much time. In my second table the OldRollNo Column is unique.One more thing is that in the resultant RollNo column if the newly assigned RollNo is already present then it should be copied exactly to the next column i.e LatestRollNo. I have to check only those RollNo which are old. Thanks.

4

4 回答 4

1

尝试这样的事情:

select t1.ID
  , t1.Name
  , t1.RollNO
  , LatestRollNO = coalesce(n.NewRollNo, o.NewRollNo)
from t1
  left join t2 o on t1.RollNO = o.OldRollNo
  left join t2 n on t1.RollNO = n.NewRollNo

SQL Fiddle 与演示

听起来您的问题是性能而不是逻辑;t2.OldRollNo假设您在and上有适当的索引,这样的事情应该有望允许适当的索引使用t2.NewRollNo

ORor CASEin子句的问题WHERE在于它们并不总是适合有效的查询。希望这对您的情况会更有用。

于 2013-07-17T10:10:01.600 回答
1

您需要使用内部连接。

SELECT t1.ID,t1.Name,t2.RollNo,t2.NewRollNo AS LatestRollNo
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.RollNo=t2.OldRollNo OR t1.RollNo=t2.NewRollNo
于 2013-07-17T10:01:16.440 回答
1
select f.ID, f.name, f.RollNo, s.NewRollNo as "Latest RollNo"
from FirstTable f 
inner join 
SecondTable s on f.RollNo = s.OldRollNo or f.RollNo = s.NewRollNo
于 2013-07-17T10:01:20.420 回答
1
select t.id,t.name,t.rollno,tt.newrollno as latestrollno from
talble1 t
left join
table2 tt on t.rollno = tt.oldrollno
于 2013-07-17T10:03:43.340 回答