2011-10-04 49 views
0

我有一個表這樣找到下一個ID表中的SQL查詢..用於在特定類別

Categories table 
    ------------------- 
    ID Cat_Name 
    1 cat1 
    2 cat2 
    3 cat3 

Stations table 
------------------ 
ID Sta_Name Cat_ID 
1 sta1  1 
2 sta2  3 
3 sta3  2 
4 sta4  1 
5 sta5  1 
6 sta6  3 

現在我需要我有唯一的ID輸入作爲1(即,第一行第一山坳VAL),所以現在我想輸出4

因爲該類別中的下一個項目是在這個意義上我得到了1,4,6,9編號的第1類4

下一個項目所以現在我有輸入6現在輸出必須是9,因爲如果我給了輸入9,輸出必須返回1

+1

對於MySQL或SQL-Server?或兩者? –

回答

0

我不確定您的意思是「下一個」,訂單如何確定。無論如何,這是基本的方法:

select t2.ID 
from MyTable t1 
inner join MyTable t2 on t1.Cat_ID = t2.Cat_ID and t1.ID <> t2.ID 
+0

下一個項目在這個意義上,我得到了1,4,6,9 id在類別1所以 現在我有輸入6現在輸出必須是9,因爲類別1中的下一項6是9 如果我給了輸入9輸出必須返回1 – Siddhartha

0
select t2.id 
from mytable t1 
inner join mytable t2 on t2.cat_id = t1.cat_id and t2.id > t1.id 
limit 1 
0

上爲別人太..是1你想用同一類ID 1(因此ID找到下一個ID的ID有些不清楚4也是一樣的Cat_ID 1)?我會嘗試

select MIN(S2.ID) as NextID 
    from 
     Stations S1 
     JOIN Stations S2 
      on S1.Cat_ID = S2.Cat_ID 
      AND S2.ID > S1.ID 
    where 
     S1.ID = IDYouAreInterestedIn 

我已經改名爲表和別名,以配合您的新表的編輯......在這種情況下,「S1」和「S2」的「別名」你的「站」表。

Join命令基於表格之間的相同類別,但此外,只包含第二個實例中的ID比您開始的ID更大的記錄(在您的情況下,您正在尋找1 )..您不希望返回1作爲您開始的1條記錄的答案。你想要的第一個數字在你之後。

所以,從最新的樣本......

Stations table 
------------------ 
ID Sta_Name Cat_ID 
1 sta1  1 
2 sta2  3 
3 sta3  2 
4 sta4  1 
5 sta5  1 
6 sta6  3 


IF you enter The next ID would be 
ID = 1   4 (both category 1) 
ID = 2   6 (the next instance of category 3) 
ID = 3   No record found... no other "2" category 
ID = 4   5 (first ID after 4 but same "1" category) 
ID = 6   No record since nothing after 6 in the list. 
+0

YT2.ID> YT1.ID ???我不明白這一點:( – Siddhartha

+0

@siddhartha,請參閱您的修訂內容示例 – DRapp

+0

修訂答案我無法得到與上述查詢的答案你試過它..它返回我空 和.. 在你的例子如果ID = 6,它必須返回ID 2 ... – Siddhartha

1

如果我理解一個好的方法是...

僅考慮了「電臺表」和當前站ID

-- the one for next station 
SELECT MIN(ID) as next FROM `stations` WHERE Cat_ID = {desidered_Cat_ID} AND ID > {your_current_ID} LIMIT 1; 

-- the one for previous station 
SELECT MAX(ID) as prev FROM `stations` WHERE Cat_ID = {desidered_Cat_ID} AND ID < {your_current_ID} LIMIT 1; 

希望這有助於。