Question

The query I am trying to perform is

With getusers As
    (Select userID from userprofspecinst_v where institutionID IN
    (select institutionID, professionID from userprofspecinst_v where userID=@UserID) 
    and professionID IN 
    (select institutionID, professionID from userprofspecinst_v where userID=@UserID))

    select username from user where userID IN (select userID from getusers)

Here's what I'm trying to do. Given a userID and a view which contains the userID and the ID of their institution and profession, I want to get the list of other userID's who also have the same institutionID and and professionID. Then with that list of userIDs I want to get the usernames that correspond to each userID from another table (user). The error I am getting when I try to create the procedure is, "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.". Am I taking the correct approach to how I should build this query?

Was it helpful?

Solution

The following query should do what you want to do:

SELECT      u.username

FROM        user AS u
INNER JOIN  userprofspecinst_v AS up ON u.userID = up.userID
INNER JOIN  (SELECT institutionID, professionID FROM userprofspecinst_v 
                 WHERE userID = @userID) AS ProInsts
                     ON (up.institutionID = ProInsts.institutionID 
                                 AND up.professionID = ProInsts.professionID)

Effectively the crucial part is the last INNER JOIN statement - this creates a table constituting the insitutionsids and professsionids the user id belongs to. We then get all matching items in the view with the same institution id and profession id (the ON condition) and then link these back to the user table on the corresponding userids (the first JOIN).

You can either run this for each user id you are interested in, or JOIN onto the result of a query (your getusers) (it depends on what database engine you are running).

If you aren't familiar with JOIN's, Jeff Atwood's introductory post is a good starting place.

The JOIN statement effectively allows you to explot the logical links between your tables - the userId, institutionID and professionID are all examples of candidates for foreign keys - so, rather than having to constantly subquery each table and piece the results together, you can link all the tables together and filter down to the rows you want. It's usually a cleaner, more maintainable approach (although that is opinion).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top