我想从/向电子邮件first@test.com
选择所有电子邮件( domain_name.emails.id = 1
)。 (作为收件人,作为发件人)
id | from | message
1 | first@test.com | A
2 | second@test.com | B /* Because second sent email to first */
我有:
SELECT
c.*
FROM
domain_name.emails AS a
INNER JOIN domain_names AS b ON b.ID = a.domain_name_id
INNER JOIN email.messages AS c ON c.from = ( a.NAME || '@' || b.NAME || '.' || b.domain_id )
INNER JOIN email.message_recipients AS d ON d.recipient = ( a.NAME || '@' || b.NAME || '.' || b.domain_id )
WHERE
a.ID = 1;
注意:" INNER JOIN"对不对?
我明白了:
id | from | message
1 | first@test.com | A
表格(仅2个FK)
电子邮件架构类似于LOG
domain_name.emails
id | domain_name_id (domain_names.id FK) | name
1 | 1 | first
domain_names
id | domain_id | name
1 | com | test
email.messages
id | from | message
1 | first@test.com | A
2 | second@test.com | B
email.message_recipients
id | message_id (email.messages.id FK) | recipient
1 | 1 | second@test.com
2 | 2 | first@test.com
答案 0 :(得分:0)
我认为你可以使用这样的查询 - 未经测试 - :
-- In fromTo I merge `TO`s data after `FROM`s data
;with fromTo as (
select *
from email.messages
union all
select message_id, recipient, c.message
from email.message_recipients d
join email.messages c on c.id = d.message_id
)
select
c.*
from
domain_name.emails a
join domain_names b on b.ID = a.domain_name_id
join fromTo c on c.from = ( a.NAME || '@' || b.NAME || '.' || b.domain_id )
where
a.ID = 1;
答案 1 :(得分:0)
您需要合并这两个包含电子邮件地址的表:
SELECT
c.*
FROM domain_name.emails AS a
INNER JOIN domain_names AS b ON b.ID = a.domain_name_id
INNER JOIN (SELECT id AS message_id, "from" AS address FROM email.messages
UNION
SELECT message_id, recipient FROM email.message_recipients
) AS m ON m.address = ( a.NAME || '@' || b.NAME || '.' || b.domain_id )
INNER JOIN email.messages AS c ON c.id = m.message_id
WHERE
a.ID = 1;