SQL重复值,其中value为NULL

时间:2017-06-20 20:42:36

标签: mysql sql

我创建了一个摘要视图,并使用以下查询来获得结果

    SELECT captain.Name AS Name,
      rides.date AS date,
      rides.tr AS tr,
      rides.cr AS cr,
      rides.cg AS cg,
      rides.p AS p,
      rides.oe AS oe,
      (((rides.cr + rides.cg) - (rides.p +
      rides.oe)) - rides.tih) AS short,
     rides.tih AS tih,
     ct.tr AS tr,
     ct.ca AS ca
   FROM (rides
     JOIN captain ON captain.captainID = rides.captainID)
     JOIN ct ON captain.captainID = ct.captainID

像这样输出

date      tr    cr  cg  p   oe  short   tih tr  ca
---------------------------------------------------
12/6/2017 20    10  10  2   3    4      43  1   88
13/6/2017 10    9   9   2   3    1      56  1   88
14/6/2017 20    10  10  2   3    4      43  1   88
15/6/2017 10    9   9   2   3    1      56  1   88
16/6/2017 20    10  10  2   3    4      43  1   88
17/6/2017 10    9   9   2   3    1      56  1   88 

但它应该是

date      tr    cr  cg  p   oe  short   tih tr  ca
---------------------------------------------------
12/6/2017 20    10  10  2   3    4      43  0   0
13/6/2017 10    9   9   2   3    1      56  0   0
14/6/2017 20    10  10  2   3    4      43  0   0
15/6/2017 10    9   9   2   3    1      56  0   0
16/6/2017 20    10  10  2   3    4      43  1   88
17/6/2017 10    9   9   2   3    1      56  1   88 

因为在ct表中我只有6月16日和17日的两条记录。 如果没有可用的记录,如何强制显示0。

希望我已经正确解释了我需要什么。提前谢谢。

2 个答案:

答案 0 :(得分:0)

在最后一行使用LEFT JOIN(左外连接)。

SELECT captain.Name AS Name,
  rides.date AS date,
  rides.tr AS tr,
  rides.cr AS cr,
  rides.cg AS cg,
  rides.p AS p,
  rides.oe AS oe,
  (((rides.cr + rides.cg) - (rides.p +
  rides.oe)) - rides.tih) AS short,
 rides.tih AS tih,
 ct.tr AS tr,
 ct.ca AS ca
 FROM (rides
 JOIN captain ON captain.captainID = rides.captainID)
 LEFT JOIN ct ON (captain.captainID = ct.captainID and rides.date=ct.date)

答案 1 :(得分:0)

加入date以及ct table.使用case when将空白值替换为0

试试这个: -

   SELECT captain.Name AS Name,
      rides.date AS date,
      rides.tr AS tr,
      rides.cr AS cr,
      rides.cg AS cg,
      rides.p AS p,
      rides.oe AS oe,
      (((rides.cr + rides.cg) - (rides.p +
      rides.oe)) - rides.tih) AS short,
     rides.tih AS tih,
     case when ct.tr is NULL and ct.tr=' ' then 0 else ct.tr END AS tr,
     case when ct.ca is NULL and ct.ca=' ' then 0 else ct.ca END AS ca,
   FROM (rides
     JOIN captain ON captain.captainID = rides.captainID)
    LEFT JOIN ct ON rides.captainID = ct.captainID and rides.date=ct.date