我在一个表上有178行,在另一个表上有179个用于特定顺序,但无论我做什么,我都无法通过SQL查询向我显示179行,它只显示了178行。
SELECT
rl.po, rl.item_id, rl.pieces_received,
ol.order_id, ol.item_id, ol.pieces_shipped
FROM
receipt_lines rl
LEFT JOIN
hi_order_lines ol ON rl.item_id = ol.item_id
WHERE
ol.order_id = 'TR0202379'
AND rl.po = 'TR0202379'
我也试过
SELECT
rl.po, rl.item_id, rl.pieces_received,
ol.order_id, ol.item_id, ol.pieces_shipped
FROM
receipt_lines rl
LEFT JOIN
hi_order_lines ol ON rl.item_id = ol.item_id
AND ol.order_id = 'TR0202379'
AND rl.po = 'TR0202379'
在查询的其他变体中,但我不知道可能出现的问题。
只是添加一些数据用于可视化目的..
PO item_id pieces_received order_id item_id pieces_shipped
TR0202379 CM504438-BLK- M 77 TR0202379 CM504438-BLK- M 77
TR0202379 CM504438-BLK-XXL 14 TR0202379 CM504438-BLK-XXL 14
TR0202379 CM504438-BLK- S 32 TR0202379 CM504438-BLK- S 32
TR0202379 CM504438-LDN- XL 2 TR0202379 CM504438-LDN- XL 2
非常感谢任何帮助。
由于
答案 0 :(得分:1)
假设两个表上所有记录的id都是TR0202379,那么左表hi_order_lines必须是178行的表。尝试使用正确的加入。
答案 1 :(得分:1)
我认为你的第二个例子几乎就在那里,给它一个机会;
SELECT
rl.po, rl.item_id, rl.pieces_received,
ol.order_id, ol.item_id, ol.pieces_shipped
FROM
receipt_lines rl
LEFT JOIN
hi_order_lines ol ON rl.item_id = ol.item_id
AND ol.order_id = 'TR0202379'
WHERE rl.po = 'TR0202379'
这假设Receipt_Lines是包含179行的表。如果它是hi_order_lines,那么你必须将这些表转换(我真的不喜欢正确的连接),就像这样;
SELECT
rl.po, rl.item_id, rl.pieces_received,
ol.order_id, ol.item_id, ol.pieces_shipped
FROM
hi_order_lines ol
LEFT JOIN receipt_lines rl
ON rl.item_id = ol.item_id
AND rl.po = 'TR0202379'
WHERE ol.order_id = 'TR0202379'
答案 2 :(得分:0)
因为您正在使用LEFT JOIN,所以您总是会获得178行,因为您正在加入'receipt_lines',这是您的情况下的左表,LEFT JOIN不包括左表的空值,而是你可能想尝试RIGHT JOIN,这会给你剩下的一行带有allocate_lines的空值。
SELECT rl.po,rl.item_id, rl.pieces_received,ol.order_id,ol.item_id,ol.pieces_shipped FROM receipt_lines rl
RIGHT JOIN hi_order_lines ol
ON rl.item_id=ol.item_id
WHERE ol.order_id='TR0202379' AND rl.po='TR0202379'
或者您可以按如下方式切换查询:
SELECT rl.po,rl.item_id, rl.pieces_received,ol.order_id,ol.item_id,ol.pieces_shipped FROM hi_order_lines ol
LEFT JOIN receipt_lines rl
ON rl.item_id=ol.item_id
WHERE ol.order_id='TR0202379' AND rl.po='TR0202379'