mysql left join 重复我的表行 - 为什么?

标签 mysql sql

我有 2 张 table :

  • Table1 => Product_id, Product_quantity => 这里有 25 行。
  • Table2 => Product_hashid, order_quantity => 这里我有 1 个查询行。

我构建了这个 mysql 查询:

SELECT SUM(table1.product_quantity) - SUM(order_quantity) AS instocks
  FROM table1  -- table.1 in original
  LEFT JOIN table2 ON table2.product_hashid = table1.product_id
 WHERE table1.product_id = '$thisid'

此查询将 table2 行与 table1 重复。此查询是否有错误?

首先,我想对 table1product_id = '$this' 中的所有 product_quantity 求和,并对所有 order_quantity 求和code> in table2 where product_hashid = '$this' 并 make (a - b) 显示最终结果。

最佳答案

您对自己想做的事情的概述很好,但这不是您实现的。

  • I want to sum all product_quantity from table1 where product_id = '$this' and sum all order_quantity in table2 where product_hashid = '$this' and make (a - b) to display a final result.

一步一步地构建它。

SELECT SUM(product_quantity) FROM Table1 WHERE Product_ID = '$this';

SELECT SUM(order_quantity) FROM Table2 WHERE Product_HashID = '$this';

SELECT (SELECT SUM(product_quantity) FROM Table1 WHERE Product_ID     = '$this') -
       (SELECT SUM(order_quantity)   FROM Table2 WHERE Product_HashID = '$this')
  FROM Dual;

您可能会发现代码对齐强​​调了产品 ID 列的不一致的列命名。


在更一般的情况下:

SELECT Product_ID, SUM(product_quantity) AS Product_Quantity
  FROM Table1
 GROUP BY Product_ID;

SELECT Product_HashID AS Product_ID, SUM(order_quantity) AS Order_Quantity
  FROM Table2
 GROUP BY Product_HashID;

SELECT p.Product_ID, p.Product_Quantity - o.Order_Quantity AS SurplusOnHand
  FROM (SELECT Product_ID, SUM(product_quantity) AS Product_Quantity
          FROM Table1
         GROUP BY Product_ID) AS P
  JOIN (SELECT Product_HashID AS Product_ID, SUM(order_quantity) AS Order_Quantity
          FROM Table2
         GROUP BY Product_HashID) AS O
    ON O.Product_ID = P.Product_ID;

有时您需要使用 LEFT OUTER JOIN;大多数情况下,你不知道。假设您不这样做,然后编写 SQL,直到您确信您这样做为止。

鉴于数据基数(行数),您可能需要在此处执行 LOJ。对于表1中列出的、表2中未列出的产品,您需要将订单数量制造为零。

SELECT    (SELECT SUM(product_quantity) FROM Table1 WHERE Product_ID     = '$this') -
       NVL(SELECT SUM(order_quantity)   FROM Table2 WHERE Product_HashID = '$this'), 0)
  FROM Dual;


SELECT p.Product_ID, p.Product_Quantity - NVL(o.Order_Quantity, 0) AS SurplusOnHand
  FROM (SELECT Product_ID, SUM(product_quantity) AS Product_Quantity
          FROM Table1
         GROUP BY Product_ID) AS P
  LEFT OUTER JOIN
       (SELECT Product_HashID AS Product_ID, SUM(order_quantity) AS Order_Quantity
          FROM Table2
         GROUP BY Product_HashID) AS O
    ON O.Product_ID = P.Product_ID;

关于mysql left join 重复我的表行 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6167743/

相关文章:

php - 从数据库返回计数

python - 无法使用 python 连接到 mysql db - 握手不好

mysql - 在 MySQL 中创建具有空值的 VIEW

sql - Q : How to find same and similar string values in different tables in SQL

mysql - 使用 SQL 将 json 数据列表字段转换为列

mysql - 我无法弄清楚该SQL查询中的错误在哪里

php - utf8 编码在 php 中无法正常工作

mysql - 从没有本地化的SQL中选择数据

sql - 如何进行递归查询

mysql - 包含多个 'Not Like' 的 Where 语句