mysql查询时做关联表LEFT JSON过滤条件ON中存在 AND d.invoice_code = m.invoice_code,当invoice_code == null,不使用AND d.invoice_code = m.invoice_code如何操作
时间: 2024-09-10 17:21:51 浏览: 47
在MySQL中,如果你想要在LEFT JOIN中处理`invoice_code`可能为NULL的情况,并避免在条件中直接使用`AND d.invoice_code = m.invoice_code`,你可以使用`COALESCE()`函数来替代。`COALESCE()`函数返回第一个非NULL参数,这样即使`d.invoice_code`为空,也可以匹配`m.invoice_code`。
下面是如何修改你的SQL语句的示例:
```sql
SELECT c.client_id, c.name, COALESCE((SELECT SUM(i.invoice_total) FROM invoices i WHERE i.client_id = c.client_id), 0) AS total_sales
FROM clients c
LEFT JOIN invoices d ON COALESCE(d.invoice_code, '') = COALESCE(m.invoice_code, '')
WHERE d.invoice_code IS NOT NULL OR d.invoice_code IS NULL AND m.invoice_code IS NULL;
```
在这个例子中,我们使用`COALESCE(d.invoice_code, '')`将`invoice_code`转换为字符串,这样即使它为NULL,也会与空字符串相比较。`OR d.invoice_code IS NULL AND m.invoice_code IS NULL`这部分则确保了在`invoice_code`一方为空而另一方也为空(即双方都为NULL)的情况下,仍然能够匹配。
阅读全文