使用LEFT JOIN没有结果时,Mysql列不能为null错误

时间:2016-07-20 14:35:42

标签: mysql sql subquery left-join

我在客户表中有一些数据,其他表中没有数据。因此,当我尝试使用以下查询进行选择时,它会给我

  

1048-列'customerid'不能为空

。可能是什么问题呢。有解决方案吗?

SELECT c.*, fd.ruakzat as ruak,
        fd.khatzat as khat, 0+0 as belh, 0+0 as neih, 
        puk.lended as hawh
        FROM `customer` c
        LEFT JOIN ( 
                SELECT s.customerid, o.orderzat as ruakzat, 
                       f.filled as khatzat     
                FROM `sale` s    
                LEFT JOIN (     
                       SELECT SUM(quantity) as orderzat,invoiceno     
                       FROM `order`    
                       WHERE fillstatus='Empty'
                       GROUP BY invoiceno    
                 ) AS o ON s.invoiceno=o.invoiceno    
                LEFT JOIN (     
                      SELECT SUM(quantity) as filled,invoiceno    
                      FROM `order`    
                      WHERE fillstatus='Filled'    
                      GROUP BY invoiceno    
                ) AS f ON s.invoiceno=f.invoiceno    
        ) AS fd ON c.id=fd.customerid    
        LEFT JOIN (     
             SELECT SUM(quantity) as lended, customerid    
             FROM `lending`    
        ) AS puk ON c.id=puk.customerid     
       WHERE (puk.customerid IS NULL OR c.name LIKE '%%')

什么是更好的方法?谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

MySQL针对类似问题(https://bugs.mysql.com/bug.php?id=31450https://bugs.mysql.com/bug.php?id=35633https://bugs.mysql.com/bug.php?id=52441)提供了一些错误报告,因此您可能遇到了相同的错误。

总结一下:如果有问题的字段按定义是不可为空的(在create table中定义为非null),但是出现在子查询中,其中输出结果可能为null。

请检查您的MySQL版本,因为它可能是上面列出的错误之一出现的版本。

此外,对我来说子查询

         SELECT SUM(quantity) as lended, customerid    
         FROM `lending`    

没有多大意义,因为没有一个部分。这会将借出表折叠成单个记录,并从其中一个记录中随机选择customerid。所以,我会在上面的子查询中添加group by customerid

答案 1 :(得分:1)

与您的问题无关,但您可以替换这两个加入

        LEFT JOIN (     
               SELECT SUM(quantity) as orderzat,invoiceno     
               FROM `order`    
               WHERE fillstatus='Empty'
               GROUP BY invoiceno    
         ) AS o ON s.invoiceno=o.invoiceno    
        LEFT JOIN (     
              SELECT SUM(quantity) as filled,invoiceno    
              FROM `order`    
              WHERE fillstatus='Filled'    
              GROUP BY invoiceno   

使用Conditional SUM

的单个人
        LEFT JOIN (     
               SELECT invoiceno, 
                      SUM(CASE WHEN fillstatus='Empty' THEN quantity
                                                       ELSE 0
                          END) as orderzat,     
                      SUM(CASE WHEN fillstatus='Filled' THEN quantity
                                                        ELSE 0
                          END) as filled     
               FROM `order`    
               GROUP BY invoiceno    
         ) AS o ON s.invoiceno=o.invoiceno