SQL子查询

时间:2010-09-08 00:31:42

标签: c# sql

我有以下查询:

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

我需要将上述查询返回的id与另一个表交叉引用以获取用户的用户名。我怎么能在一个查询中做到这一点?

现在我正在这样做:

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

预期的列输出:

id   subject   date   username
--------------------------------

3 个答案:

答案 0 :(得分:2)

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 

当然,如果你想在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
     };

答案 1 :(得分:1)

使用:

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

答案 2 :(得分:0)

SELECT username FROM users WHERE id IN (
  SELECT id FROM mail WHERE date > some_date
)