gpt4 book ai didi

mysql - 显示未订购/未出现在发票上的产品的 sql 查询

转载 作者:行者123 更新时间:2023-11-29 05:52:42 25 4
gpt4 key购买 nike

Tables joined我有一个作业问题我遇到了一些麻烦。我被问及我们数据库中从未售出的产品总数。 TABLES

它应该是这样的:

+--------------------------------------------+
| number of products that have not been sold |
+--------------------------------------------+
| 228 |
+--------------------------------------------+

我不断得到这个:

+--------------------------------------------+
| number of products that have not been sold |
+--------------------------------------------+
| 0 |
+--------------------------------------------+

我的查询是:

SELECT count(*) AS 'number of products that have not been sold'  
FROM orderdetail
JOIN invoice on invoice.invoiceid=orderdetail.invoiceid
WHERE productid is null;

最佳答案

  • 由于您要考虑所有产品,product 表必须是您在Join 中的起始表。
  • 执行左连接而不是内连接。否则,Inner Join 将消除没有可用匹配订单行的所有产品。
  • 使用 ProductID 加入 orderDetail
  • 要计算所有没有订单的产品,请使用 COUNT()功能

尝试以下操作:

SELECT count(p.ProductID) AS 'number of products that have not been sold'  
FROM product AS p
LEFT JOIN orderDetail AS od ON od.ProductID = p.ProductID
WHERE od.productid IS NULL

关于mysql - 显示未订购/未出现在发票上的产品的 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52654548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com