2014-01-16 43 views
0

有沒有辦法從表其中userid有很多獲得用戶名列表,從表中選擇用戶名其中,用戶id = {1,2,3,4,...,N}

userId  userName 
1    abc 
2    xyz 
3    pqr 

請seaa查詢我希望通過jdbcTemplate執行以下,

String query = "Select userName from table_1 where userId = {1,2,3}"; 

HashMap<int,String> = jdbcTemplate.queryForMap(sql); 

// HashMap - int : userId, String - userName 

回答

3

你應該使用

select userName from Table where user_id in (1, 2, 3); 
1

是,@Stelian Galimati我想說回答您直接提問。但是,如果想要更靈活地查詢查詢,我會建議查找嵌套的SQL選擇。 This may be a helpful beginners tutorial給你。另外,還有this可以讓你測試你的SQL。這方面的一個簡單的例子是:

SELECT userId 
FROM table_1 
WHERE userName IN { 
    SELECT userName 
    From table_2 
    WHERE userLastName = "Smith" 
} 

爲了詳細說明@Stelian Galimatis回答,如果你想選擇任意數量的給定數量的參數(可能是對象和不是int值)USER_NAMES你可以附加使用命名參數,例如,

SELECT userName 
FROM table_1 
WHERE userId IN { 
    :user1, 
    :user2, 
    :user3, 
} 

附加的教程,你可以在Tutorials Point找到你更有幫助。

+0

感謝Prancer的詳細說明。 – user1010399