没有订单商品的sql订单不会给出结果

时间:2014-10-17 14:33:13

标签: sql oracle

我想要的结果是关于一个订单的信息。当我的订单有一些订单时,下面的查询工作正常,但一旦它是一个空的订单它不提供任何信息。例如我的orderid = 5,而且这个还没有任何项目。我使用orderitems来计算订单的总成本。如果没有订购,我如何获取我的信息?这是我的查询:

SELECT DISTINCT 
  u.firstname|| ' ' || u.lastname, 
  TO_CHAR(o.date,'DD-MON-YY HH24:mm'),
  (SELECT SUM(oItem.amount * oItem.pricewhenordered) FROM ORDERITEM oItem WHERE 
  oItem.ORDERID=o.ID), 
  (case o.employeeid
    when null then '-'
    else (SELECT us.firstname|| ' ' || us.lastname FROM user us WHERE 
    id=o.employeeid)
  END), 
  o.status
FROM order o, orderitem oItem, user u
WHERE o.userid = u.id
AND o.id = oItem.orderid
AND o.id = 5;

TABLES
order ID, 用户身份, 日期, 状态, employeeid

orderitem 订单ID, 产品ID, 量, pricewhenordered

user ID, 用户名, 密码, 名字, 姓, usertypeid

2 个答案:

答案 0 :(得分:1)

明确你的联接并在没有项目的情况下使用LEFT联接应该可以胜任。

SELECT DISTINCT 
  u.firstname|| ' ' || u.lastname, 
  TO_CHAR(o.date,'DD-MON-YY HH24:mm'),
  (SELECT SUM(oItem.amount * oItem.pricewhenordered) FROM ORDERITEM oItem WHERE 
  oItem.ORDERID=o.ID), 
  (case o.employeeid
    when null then '-'
    else (SELECT us.firstname|| ' ' || us.lastname FROM user us WHERE 
    id=o.employeeid)
  END), 
  o.status
FROM order o
LEFT OUTER JOIN orderitem oItem ON  o.id = oItem.orderid
INNER JOIN user u ON o.userid = u.id
WHERE o.id = 5;

答案 1 :(得分:1)

您实际上并未在主查询中使用ORDERITEM(oitem)表;把它留下来:

SELECT DISTINCT 
  u.firstname|| ' ' || u.lastname, 
  TO_CHAR(o.date,'DD-MON-YY HH24:mm'),
  (SELECT SUM(oItem.amount * oItem.pricewhenordered) 
     FROM ORDERITEM oItem 
    WHERE oItem.ORDERID=o.ID), 
  (case o.employeeid
        when null 
        then '-'
        else (SELECT us.firstname|| ' ' || us.lastname 
                FROM user us 
               WHERE id=o.employeeid)
        END), 
  o.status
FROM 
    order o, user u
WHERE 
    o.userid = u.id
    AND o.id = 5;