2010-09-08 162 views
0

我有以下查詢: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 
-------------------------------- 
+0

爲了澄清,你想運行一個查詢來獲取'MAIL.id','MAIL.subject','MAIL.date'和'USERS .username'? – 2010-09-08 00:38:10

+0

@OMG Ponies yes – Arizona1911 2010-09-08 00:40:50

回答

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 
+0

爲什麼JOIN中的「AND u.id = {0}」部分而不是WHERE? – 2010-09-08 15:13:50

+0

@James Curran:因爲使用了INNER join,所以放置並不重要。如果它是一個OUTER連接,那麼'USERS.id'過濾將發生在JOIN之前,並可能影響結果集。 – 2010-09-08 15:34:10

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

該OP澄清,希望從這兩個表的列。 – 2010-09-08 00:56:22

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 

賽道中E,如果你想在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 
    };