如何根据第二个表中的值从mysql表中进行选择

时间:2014-06-30 10:35:08

标签: mysql

我有一个包含电子邮件的表格电子邮件,例如:

EmailID DateStamp                Subject
8       2014-04-03 10:56:10.000  Subject of the Email
9       2014-02-25 08:52:10.000  Subject of the Email
10      2014-04-13 12:22:25.000  Subject of the Email
11      2014-02-15 11:18:16.000  Subject of the Email
12      2014-03-20 09:26:04.000  Subject of the Email

然后我有第二个表EmailDirection连接用户ID和电子邮件ID,其中DirectionID是一个数字代码,表示:1 = FROM; 2 = TO; 3 = CC,4 = BCC

EmailID ProfileID DirectionID
10      72        1
10      91        2
10      58        2
10      57        3
10      24        3
10      44        3

我希望建立一个独特的表格,我只有四列:

emailID    datestamp               sender    receiver
10         2014-04-13 12:22:25.000 72        91
10         2014-04-13 12:22:25.000 72        58
10         2014-04-13 12:22:25.000 72        57
10         2014-04-13 12:22:25.000 72        24
10         2014-04-13 12:22:25.000 72        44

其中发件人是发送电子邮件的用户,而接收者是收到电子邮件的用户,无论是直接还是CC和BCC。到目前为止我的代码是:

 SELECT Email.EmailID as 'id', Email.DateStamp as 'timed', 
 EmailDirection.ProfileID as 'sender' where profileID in (Select profileid from EmailDirection where directionid = 1), 
 EmailDirection.ProfileID as 'receiver' where profileid in (select profileid from EmailDirection where directionid != 1)
FROM Email, EmailDirection
WHERE Email.EmailID = EmailDirection.EmailID

但我收到错误代码1064 ...我明白我的问题是在select语句中指定发送方和接收方的directionId,但我无法解决这个简单的谜题......

2 个答案:

答案 0 :(得分:1)

您应该将此作为多个连接进行处理。特别是,您需要为电子邮件的“从”和“到”部分单独加入:

SELECT e.EmailID as id, e.DateStamp as timed, 
       edfrom.profileid as sender, edto.profileid as receiver
FROM EmailDirection edfrom join
     Email e
     on edfrom.emailid = e.emailid and ed.direction = 1 join
     EmailDirection edto
     on edto.emailid = e.emailid and ed.direction <> 1;

还有两条评论。首先,只对字符串和日期常量使用单引号。将它们用于列名称可能会导致问题。其次,学习正确的显式join语法。通常:在from子句中使用逗号。

答案 1 :(得分:0)

您必须加入表格:

SELECT Email.EmailID as 'id', Email.DateStamp as 'timed', 
 sender.ProfileID as 'sender'  receiver.ProfileID as 'receiver' 
FROM Email join  EmailDirection sender on sender.EmailID = email.EmailID and sender.directionid=1
join  EmailDirection receiver on receiver.EmailID = email.EmailID and receiver.directionid!=1

!!!未经测试!!!