Mysql 使用 LEFT JOIN 没有结果时出现 Column cannot be null 错误

Mysql Column cannot be null error when there is no result using LEFT JOIN

我在客户 table 中有一些数据,而在其他 table 中没有数据。因此,当我尝试 select 使用以下查询时,它给了我

1048-Column 'customerid' cannot be null

。可能是什么问题呢。有解决办法吗?

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 '%%')

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

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

总结一下:如果相关字段根据定义是不可空的(在创建 table 中定义为非空),但出现在输出结果可能为空的子查询中。

请检查您的 MySQL 版本,因为该版本可能确实出现了上面列出的错误之一。

此外,对我来说子查询

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

没有太大意义,因为没有按部分分组。这会将贷款 table 合并为一条记录,并从其中一条记录中随机选择 customerid。所以,我会在上面的子查询中添加一个 group by customerid

与你的问题无关,但你可以替换那两个join

        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