我有一个数据库,可以保留不同商店之间的所有产品交换。这是表格:
交货表:
+-------------+-----------+----------------+---------+
| delivery_id | origin_id | destination_id | ongoing |
+-------------+-----------+----------------+---------+
| 15 | 1 | 2 | 1 |
| 16 | 3 | 4 | 0 |
+-------------+-----------+----------------+---------+
站点表:
+---------+------------+----------------+
| site_id | name | address |
+---------+------------+----------------+
| 1 | site_1 | ... |
| 2 | site_2 | ... |
+-------------+--------+----------------+
原始ID和目标ID是引用site_id的外键。
我的目标是列出所有正在进行的交货,并注明来源和目的地商店的名称。对于上面给出的示例,预期结果将是:
+---------+------------+
| origin |destination |
+---------+------------+
| site_1 | site_2 |
+---------+------------+
目前,我发现选择带有关联传递ID的目的地ID和起点ID,然后将这两个结果结合起来的唯一方法:
SELECT origin.origin, destination.destination FROM
(SELECT site.name AS origin,delivery.delivery_id FROM delivery INNER JOIN site on site.site_id=delivery.origin_id WHERE delivery.ongoing=1) origin
INNER JOIN (SELECT site.name as destination,delivery.delivery_id FROM delivery INNER JOIN site ON site.site_id=delivery.destination_id WHERE delivery.ongoing=1) destination
ON origine.code=destination.code
我敢肯定,有一种更简单,更有效的方法来执行此操作,但我找不到它。有人可以确认吗?
答案 0 :(得分:3)
您似乎只想要两个联接:
select so.name as origin_name, sd.name as destination_name
from deliveries d left join
sites so
on d.origin_id = so.site_id left join
sites sd
on d.destination_id = sd.site_id
where d.ongoing = 1;
此方法使用left join
,以防delivery
中的一列具有NULL
值的情况。在这种情况下,实际上似乎不太可能,因此可能不需要外部联接。