我有2个mysql查询, 1是选择所有分支股票,其他是选择股票计数列表。 我需要选择所有未包含在库存盘点中的分支库存(通过考虑库存条形码和库存批次)
我选择所有分支股票的第一个查询是
SELECT SQL_CALC_FOUND_ROWS stock_id ,product_name , stock_batch,stock_barcode
FROM stock INNER JOIN product ON product_id = stock_product
LEFT JOIN packing ON product_package=packing_id
WHERE stock_branch = 2 AND stock_available_flg = 1
group by stock_id
和选择计数库存清单的第二个查询是
SELECT SQL_CALC_FOUND_ROWS stock_id,stock_barcode, product_name,stock_batch FROM stock_count_item
INNER JOIN stock ON stock_id = stock_count_item_stock
INNER JOIN product ON stock_product = product_id
INNER JOIN category ON category_id = product_category
WHERE stock_count_item_stock_count = 42 GROUP BY stock_barcode
我需要的是选择所有未包含在具有相同条形码和批次的库存数量中的分支库存
我的查询是
SELECT SQL_CALC_FOUND_ROWS stock_id ,product_name , stock_batch,stock_barcode
FROM stock
INNER JOIN product ON product_id = stock_product
LEFT JOIN packing ON product_package=packing_id
WHERE stock_branch = 2 AND stock_available_flg = 1 AND ( stock_batch,stock_barcode)
not in
(SELECT stock_batch ,stock_barcode FROM stock_count_item
INNER JOIN stock ON stock_id = stock_count_item_stock
INNER JOIN product ON stock_product = product_id
INNER JOIN category ON category_id = product_category WHERE stock_count_item_stock_count = 42)
但这并没有给出正确的结果。我如何考虑stock_batch,stock_barcode来纠正这个?
答案 0 :(得分:1)
使用NOT EXISTS代替NOT IN
但是,因为您还没有确定每个列来自哪些表,因此我(或任何维护代码的人)无法通过阅读查询来了解列的来源。 总是按照表格(或表格的别名)为列添加前缀。
SELECT
SQL_CALC_FOUND_ROWS stock_id
, product_name
, stock_batch
, stock_barcode
FROM stock
INNER JOIN product ON product_id = stock_product
LEFT JOIN packing ON product_package = packing_id
WHERE stock_branch = 2
AND stock_available_flg = 1
NOT NOT EXSTS (
SELECT 1
FROM stock_count_item
INNER JOIN stock ON stock_id = stock_count_item_stock
INNER JOIN product ON stock_product = product_id
INNER JOIN category ON category_id = product_category
WHERE stock_count_item_stock_count = 42
and outer_alias.stock_batch = inner_alias.stock_batch
and outer_alias.stock_barcode = inner_alias.stock_barcode
)
;
我试图用
来表明需要什么和 outer_alias .stock_batch = inner_alias .stock_batch
" outer_alias"是来自之前的 NOT EXISTS子查询的别名(或表名),而inner_alias是反向的。如果您选择使用表名作为下摆之一,则其中至少有一个必须是别名。
<强> e.g。强>
从库存中选择...不存在(...来自库存 s 和库存 .id = s < /strong>.id)
带别名的最终查询(通过下面的评论)
SELECT
SQL_CALC_FOUND_ROWS stock_id
, product_name
, s.stock_batch --<< please please please use aliases everywhere
, s.stock_barcode
FROM stock s
INNER JOIN product ON product_id = stock_product
LEFT JOIN packing ON product_package = packing_id
WHERE stock_branch = 2
AND stock_available_flg = 1
AND NOT EXISTS (
SELECT
1
FROM stock_count_item
INNER JOIN stock st ON stock_id = stock_count_item_stock
INNER JOIN product ON stock_product = product_id
INNER JOIN category ON category_id = product_category
WHERE stock_count_item_stock_count = 42
AND s.stock_batch = st.stock_batch
AND s.stock_barcode = st.stock_barcode
)