tags:

views:

42

answers:

3

I have the following query:

SELECT id, subject, date
FROM mail
WHERE date > some_date

I need to cross reference the id returned by the above query with another table to get the user's username. How can I do it in one query?

Right now I am doing this:

foreach (id in result)
{
  query = String.Format("SELECT username from USERS where id = {0}", id);
}

Expected column output:

id   subject   date   username
--------------------------------
A: 
SELECT username FROM users WHERE id IN (
  SELECT id FROM mail WHERE date > some_date
)
halfdan
The OP clarified, wants columns from both tables.
OMG Ponies
+1  A: 

Use:

SELECT m.id, 
       m.subject,
       m.date,
       u.username
  FROM MAIL m
  JOIN USERS u ON u.id = m.id
              AND u.id = {0}
 WHERE m.date > some_date
OMG Ponies
Why is the "AND u.id = {0}" part of the JOIN and not the WHERE?
James Curran
@James Curran: Because of using an INNER join, placement doesn't matter. If it were an OUTER join, the `USERS.id` filtration would occur before the JOIN and potentially affect the resultset.
OMG Ponies
+2  A: 
SELECT m.id, u.username, m.subject, m.date 
FROM mail m
inner join USERS u on m.id = u.id 
WHERE m.date > @some_date 

Of course, if you want it in C#/LINQ:

 var msgs =  from m in db.Mail
     where m.date > some_date
     select new
     {
         m.id,
         m.subject, 
         m.date, 
         m.Users.Username
     };
James Curran