使用2个外键查询表

时间:2015-12-18 10:08:02

标签: mysql sql select join union

我有4张桌子。

Mail
----
id
date

Source (can have many source)
------
id
mailID : FK Mail.id
personID : FK Person.id

Destination  (can have many destination)
-----------
id 
mailID : FK Mail.id
personID : FK Person.id

Person
------
id
name 

我尝试创建一个返回包含所有源和目标ID的邮件的查询。

到目前为止,我已经提出了这个问题,但由于它在同一个表中查询两次,效率相当低。

Select * FROM (
    Select m.*, personID, 'Source' AS TableName
    FROM Mail m join Source s 
    ON m.id = s.mailid
UNION ALL
    Select m.*, personID, 'Destination' AS TableName 
    FROM Mail m join Destination d
    ON m.id = d.mailid


) t ORDER BY id, TableName;

results:

id | date | personID | TableName
--------------------------------
 1 | 1-1-11| 3       | Source
 1 | 1-1-11| 4       | Source
 1 | 1-1-11| 5       | Source
 1 | 1-1-11| 10      | Destination
 1 | 1-1-11| 11      | Destination
 2 | 2-2-11| 1       | Source
 2 | 2-2-11| 2       | Destination

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT m.id, m.name, a.personID, a.TableName
FROM Mail m
INNER JOIN (SELECT s.mailid, s.personID, 'Source' AS TableName
            FROM Source s 
           UNION ALL
            SELECT d.mailid, d.personID, 'Destination' AS TableName
            FROM Destination d
           ) AS a ON m.id = a.mailid
ORDER BY m.id, a.TableName;