我有一个数据库表a(EMAILS),其中EmailID是主键
EmailID Email_To Email_From Email_Subject Email_Registered Email_Read
如果用户创建了一封电子邮件,则会在此表中注册。
例如,用户" Dave"谁拥有身份3发送电子邮件给"约翰"谁有id 4
所以这会给出
EmailID Email_To Email_From Email_Subject Email_Registered Email_Read
10 4 3 TEST 2/23/2016 11:00 False
要返回结果,我选择(加入用户个人资料数据库)
SELECT PROFILE_1.SellerID, PROFILE_1.Seller_UserName, EMAILS.EmailID, EMAILS.Email_From, EMAILS.Email_To, EMAILS.Email_Subject,
EMAILS.Email_Registered, EMAILS.Email_Read,
(SELECT Seller_UserName AS Epr2
FROM PROFILE
WHERE (SellerID = EMAILS.Email_To)) AS Expr2
FROM PROFILE AS PROFILE_1 LEFT OUTER JOIN
EMAILS ON EMAILS.Email_From = PROFILE_1.SellerID
WHERE (EMAILS.Email_From IS NOT NULL) AND (PROFILE_1.Seller_UserName = 'Dave')
ORDER BY EMAILS.Email_Registered DESC
John回复Dave的电子邮件,然后进入EMAILS_THREAD表并注册为
EmailThreadID EmailID Email_To Email_From Email_Registered Email_Read
1 10 3 4 2/23/2016 11:05 False
我要做的是选择
来自EMAILS的选项,其中Email_From来自Dave,并在结果中返回EMAIL_THREADS发送给Dave的前1个结果(基于Email_Registered),如果EMAIL_THREADS中有条目,则使用与EMAILS.EmailID相同的EmailID。 / p>
换句话说,如果有的话,返回EMAIL表的结果和EMAIL_THREADS表中的最新相应结果。
我希望这是有道理的。
我尝试了很多组合,我无法解决这个问题。
起初我认为这是一个子查询,或者是一个联合或一组...但我似乎无法确定选择及其结构。
寻求帮助。
这是我的最后一次尝试
SELECT PROFILE_1.SellerID, PROFILE_1.Seller_UserName, EMAILS.EmailID, EMAILS.Email_From, EMAILS.Email_To, EMAILS.Email_Subject,
EMAILS.Email_Registered, EMAILS.Email_Read,
(SELECT Seller_UserName AS Epr2
FROM PROFILE
WHERE (SellerID = EMAILS.Email_To)) AS Expr2
FROM PROFILE AS PROFILE_1 LEFT OUTER JOIN
EMAILS ON EMAILS.Email_From = PROFILE_1.SellerID CROSS JOIN
(SELECT TOP (1) EMAILS_THREAD.Email_From, EMAILS_THREAD.Email_To, EMAILS_THREAD.Email_Registered, EMAILS_THREAD.Email_Read
FROM EMAILS_THREAD LEFT OUTER JOIN
EMAILS AS EMAILS_1 ON EMAILS_THREAD.EmailID = EMAILS_1.EmailID) AS derivedtbl_1
WHERE (EMAILS.Email_From IS NOT NULL) AND (PROFILE_1.Seller_UserName = 'Dave')
ORDER BY EMAILS.Email_Registered DESC
但它根本没有从EMAILS_THREADS返回任何内容。
答案 0 :(得分:0)
来自EMAILS的选项,其中Email_From来自Dave,并在结果中返回EMAIL_THREADS的前1个结果,该结果发送给Dave(基于Email_Registered),如果EMAIL_THREADS.Hope中有条目,则使用与EMAILS.EmailID相同的EmailID这有帮助
with cte
as
(select
* from emails
where email_from=3
)
select * from cte mt --only for dave
outer apply
(
select top 1* from
emial_threads st where mt.mail_from=st.mail_to ---send to dave
and mt.emailid=st.emailid) b
答案 1 :(得分:0)
未能找到解决方案,所以我付钱给SQL专业人员为我解决这个问题。感谢Tab和The Gameiswar的输入。非常感谢。