我有两个存储电子邮件信息的表:
EMAIL:
EMAIL_ADDRESS:
假设我在EMAIL中有6行 - 查询应该返回地址的ID,时间戳。
目前我有这个:
SELECT ea.EMAIL_ADDRESS, e.ID, e.sent_date
FROM EMAIL_ADDRESS ea, CHANN_EMAIL e
WHERE e.ID=ea.id
AND ea.TYPE in ('to','from')
这将返回12行,格式为: - ,ID,日期 -from,ID,日期
查询是什么,所以我将有6行: -to,from,ID,date
答案 0 :(得分:1)
您必须将EMAIL_ADDRESS表与两个视图区分开来:
SELECT eat.EMAIL_ADDRESS as to ,ea.EMAIL_ADDRESS as from, e.ID, e.sent_date
FROM EMAIL_ADDRESS ea, CHANN_EMAIL e,EMAIL_ADDRESS eat
WHERE e.ID=ea.id and e.ID=eat.id
AND ea.TYPE in ('from') AND eat.TYPE in ('to')
答案 1 :(得分:0)
尝试使用GROUP BY e.ID
或GROUP BY ea.id
答案 2 :(得分:0)
示例数据: 电子邮件表:
| email_id | timestamp |
-------------------------------
| 1 | 2014-02-14 17:30:32.803|
| 2 | 2014-02-24 17:30:32.803|
email_address表:
| id | email_add | type |
-------------------------
| 1 |d@gmail.com| to |
| 1 |c@gmail.com| from |
| 2 |i@gmail.com| to |
| 2 |k@gmail.com| from |
查询:
SELECT tab.email_id, MAX([to]) AS [to], MAX([from]) AS [from], MAX(tab.timestamp) AS [time] FROM
(SELECT e.email_id,
CASE WHEN type= 'to' THEN ea.email_add ELSE NULL END AS [to],
CASE WHEN type= 'from' THEN ea.email_add ELSE NULL END AS [from], e.timestamp
FROM email e
INNER JOIN email_address ea
ON e.email_id = ea.id) tab
GROUP BY tab.email_id
结果:
|email_id| to | from | time |
----------------------------------------------------------
| 1 |d@gmail.com|c@gmail.com|2014-02-14 17:30:32.803|
| 2 |i@gmail.com|k@gmail.com|2014-02-24 17:30:32.803|