SELECT tro.order_id,
tro.order_code,
tol.location,
tos.token as transport_order_status
FROM transport_order tro
JOIN transport_order_location tol
ON tol.location_id = tro.location_id
JOIN transport_order_status tos
ON tos.status_id = tro.status_id
AND tos.token = 'finished';
tos.token
是唯一的varchar值。
上述SQL语句正在加入表:transport_order
,transport_order_location
和transport_order_status
。
假设我们还没有finished
个订单,那么查询将不返回任何行。
在这种情况下,我们要求显示transport_order的完整数据,并在状态中显示一些替代文本(类似not_finished
)。
答案 0 :(得分:5)
使用左连接和合并
SELECT tro.order_id,
tro.order_code,
tol.location,
COALESCE(tos.token, 'Not Finished') AS transport_order_status
FROM transport_order tro
INNER JOIN transport_order_location tol
ON tol.location_id = tro.location_id
LEFT JOIN transport_order_status tos
ON tos.status_id = tro.status_id
AND tos.token = 'finished';