Select userName from Table where userId = {1,2,3,4

2019-08-31 07:00发布

问题:

is there any way to get the list of userName from a table where userId are many,

userId      userName
1              abc
2              xyz
3              pqr

please seaa below the query i wish to execute via jdbcTemplate,

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

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

 // HashMap - int : userId, String - userName

回答1:

You should probably use

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


回答2:

Yes, @Stelian Galimati I would say answers your question directly. However, if want to have more flexibility with your querys I would recommend looking up nested SQL selects. This may be a helpful beginners tutorial for you. In addition, there is this that will allow you to test out your SQL. A quick example of this would be:

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

To elaborate on @Stelian Galimatis answer, if you wanted to select any number of user_names given a number of parameters (which may be objects and not int values) you could additionally use named parameters as such,

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

Additional tutorials you may find more helpful to you at Tutorials Point.