两个表之间的两个关系

时间:2015-10-07 14:45:44

标签: tsql

所以,我有这个简单的问题。 我们有两个表:交易和本地。

+++++++++++
|  Local  |
-----------
|id_local |
|Street   |
|ZIP      |
+++++++++++

+++++++++++++++++
|  Transaction  |
-----------------
|id_trans       |
|id_local_src   |
|id_local_dst   |
+++++++++++++++++

现在,我需要确保在交易中记录位置(来源)和位置(目的地)。 问题是我可以将关系id_local_src设为id_local,将id_local_dst设置为id_local,但这是一个问题吗?因为如果我想进行此查询,它不会向我显示:

SELECT id_trans,--How can specify street from and street to?
Street,ZIP
FROM Transactions INNER JOIN Local ON Transactions.id_local_src=Local.id_local AND Transactions.id_local_dst=Local.id_local

2 个答案:

答案 0 :(得分:1)

您可以使用table alias

SELECT id_trans,
    src.Street AS fromStreet,
    src.ZIP AS fromZIP,
    dst.Street AS toStreet,
    dst.ZIP AS toZIP
FROM Transactions INNER JOIN
    Local src ON Transactions.id_local_src = src.id_local INNER JOIN
    Local dst ON Transactions.id_local_dst = dst.id_local

答案 1 :(得分:0)

解决方案

SELECT
T.id_trans AS id_trans,
LSRC.Street AS StreetFrom,
LDST.Street AS StreetTo,
LSRC.ZIP AS ZIPFrom,
LDST.ZIP AS ZIPTo

FROM `transaction` AS T

INNER JOIN `local` AS LSRC
ON T.id_local_src = LSRC.id_local

INNER JOIN `local` AS LDST
ON T.id_local_dst = LDST.id_local