I'm not sure if I phrased that correctly but here's my dilemma. I inherited an application which needs to look up the company associated with each contact in a list. The way it is currently written the application queries the DB on the following:
SELECT c.name
FROM company c
WHERE c.id = (SELECT u.company_id
FROM user u
WHERE u.login_id = ?);
The problem is开发者_如何学C that it needs to look up thousands of users so doing this query one at a time is really inefficient. What I'd like to do is run 1 query like this:
SELECT c.name
FROM company c
WHERE c.id = (SELECT u.company_id
FROM user u
WHERE u.login_id IN LIST (?,?,?...));
But I don't know how to then match the list of users back up with the company? How do I get it to select the matched login_id along with the name?
UPDATE: How do I apply the answer below to a more complex query that pulls contract info from another DB? The current full query looks like this (This pulls multiple rows also, one for each active contract level. Eventually I also want to have it combine those into 1 with a list of all contract types so I can then run a grep on that field for the "highest" one (unless there's also a way to do a custom sort in SQL and only return the first one):
SELECT c.id,
c.name,
cs.id,
cs.name,
csc.contract_type,
csc.contract_status
FROM company c,
company_site cs,
company_site_contract csc
WHERE c.id = cs.company_id
AND cs.id = csq.site_id
AND csc.contract_status = 'ACTIVE'
AND cs.site_id IN (SELECT cs.site_id
FROM user u,
contact c,
company_site cs
WHERE c.id = u.company_id
AND cs.id = c.site_id
AND u.login_id = ?);
select c.name, u.login_id
from company c
inner join user u on u.company_id = c.id
where u.login_id in (List(?,?,?...))
if you have users that are not associated with companies then do this
select c.name, u.login_id
from user u
left join company c on c.id = u.company_id
where u.login_id in (List(?,?,?...))
精彩评论