SQL:Join条件将查询结果排除为零行。需要非空结果集

时间:2017-03-14 11:02:24

标签: sql oracle

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_ordertransport_order_locationtransport_order_status

假设我们还没有finished个订单,那么查询将不返回任何行。

在这种情况下,我们要求显示transport_order的完整数据,并在状态中显示一些替代文本(类似not_finished)。

1 个答案:

答案 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';