我有一些如下所示的代码:
SELECT *
FROM invoices
LEFT JOIN shipments ON (
shipments.id = invoices.shipment_id
)
LEFT JOIN details ON (
details.id = invoices.detail_id
)
基本上,我想通过 invoices 表中的标识符来查找 shipping 表和 details 表。但是,我还想使用以下内容加入这两个表:
SELECT *
FROM shipments
JOIN details ON (shipments.order = details.order)
基本上,如果找到(invoices.shipment_id,invoices.detail_id)中的任何一个,我想要一种拉两个表的方法。但是,我不能在连接中引用后面的表,所以我不能只做类似的事情:
SELECT *
FROM invoices
LEFT JOIN shipments ON (
shipments.id = invoices.shipment_id
OR shipments.order = details.order
)
LEFT JOIN details ON (
details.id = invoices.detail_id
)
有没有办法在拉两个表的同时做到这一点?
为清楚起见进行编辑:
这是一个示例表结构
CREATE TABLE invoices (
id integer PRIMARY KEY,
shipment_id integer,
detail_id integer,
data text
)
CREATE TABLE shipments (
id integer PRIMARY KEY,
data text
)
CREATE TABLE details (
id integer PRIMARY KEY,
shipment_id REFERENCES shipments (id),
data text
)
invoices.shipment_id
可能包含也可能不包含shipments.id
,并且invoices.detail_id
可能包含也可能不包含details.id
。
如果invoices.shipment_id
包含有效的 id,我需要执行以下操作:
SELECT
shipments.data as shipment_data,
details.data as detail_data,
FROM invoices
JOIN shipments ON (invoices.shipment_id = shipments.id)
JOIN details ON (details.shipment_id = shipments.id)
如果invoices.detail_id
包含有效的 id,我需要这样做:
SELECT
shipments.data as shipment_data,
details.data as detail_data,
FROM invoices
JOIN details ON (invoices.detail_id = details.id)
JOIN shipments ON (details.shipment_id = shipments.id)
有没有办法将这两者干净地结合在一起?