保留不匹配的行,同时在MySQL中行所在的列上进行连接

wz3gfoph  于 2022-11-21  发布在  Mysql
关注(0)|答案(1)|浏览(153)

我有两个表:current_inv和qb_inventory_levels_v。我想通过part_number连接这两个表,同时还允许它仍然显示其中一个表中只有部件编号的行。例如:
| 零件编号a|零件编号b|数量|数量_B|
| - -|- -|- -|- -|
| ABCDEFG公司|ABCDEFG公司|一个|三个|
| 中益兴威|零值|2个|零值|
| 零值|万维网|零值|一个|
我的当前查询只提供了它们重叠的部分。我尝试在stackoverflow上查找其他答案,但没有找到一个完全符合我的问题的答案。提前感谢您的帮助。我的当前查询是:

SELECT * FROM (SELECT part_number, COUNT(part_number) AS current_inv_qty FROM utility_views.current_inv GROUP BY part_number) sub_2
JOIN (SELECT part_number, SUM(quantityonhand) AS qb_qty FROM qb_inventory_levels_v a GROUP BY part_number) sub_1 ON sub_1.part_number = sub_2.part_number
WHERE current_inv_qty > qb_qty
p3rjfoxz

p3rjfoxz1#

带有可空检查的左连接应该适合您。
左连接确保您始终在输出中获得查询sub_2返回的所有part_numbers。
必须添加条件OR qb_qty IS NULL,以满足sub_1中没有零件号的那些行的需要

SELECT * 
     FROM (SELECT part_number, COUNT(part_number) AS current_inv_qty 
             FROM utility_views.current_inv 
           GROUP BY part_number) sub_2
LEFT JOIN (SELECT part_number, SUM(quantityonhand) AS qb_qty 
           FROM qb_inventory_levels_v a GROUP BY part_number) sub_1 
       ON sub_1.part_number = sub_2.part_number
    WHERE (current_inv_qty > qb_qty
       OR qb_qty IS NULL)

相关问题