LEFT JOIN - 从LEFT表选择中丢失一行

时间:2014-04-07 11:40:59

标签: mysql join

我在使用以下查询时遇到问题:

SELECT 
IFNULL(t4.ItemID, 
IFNULL(t3.ItemID, IFNULL(t2.ItemID, t1.ItemID))) AS ID, 
IFNULL(t4.ParentItemID, 
IFNULL(t3.ParentItemID, 
IFNULL(t2.ParentItemID, t1.ParentItemID))) as Parent, 
IFNULL(tp4.ItemNo, IFNULL(tp3.ItemNo, IFNULL(tp2.ItemNo, tp1.ItemNo))) AS ItemNo
FROM ItemsParents AS t1
LEFT JOIN ItemsDB AS tP1 
ON t1.ItemID = tP1.ID
LEFT JOIN ItemsParents AS t2 
ON t1.ItemID = t2.ParentItemID
LEFT JOIN ItemsDB AS tP2 
ON t2.ItemID = tP2.ID
LEFT JOIN ItemsParents AS t3 
ON t2.ItemID = t3.ParentItemID
LEFT JOIN ItemsDB AS tP3 
ON t3.ItemID = tP3.ID
LEFT JOIN ItemsParents AS t4 
ON t3.ItemID = t4.ParentItemID
LEFT JOIN ItemsDB AS tP4 
ON t4.ItemID = tP4.ID
WHERE t1.ParentItemID = 
(
SELECT ID 
FROM ItemsDB 
WHERE ItemNoInt = 359
)

此表应从选择的第一部分返回两行(822和875),并追加来自ItemsParents LEFT JOINS的更多行。它会附加新行,但原始两行中的一行会丢失   822个
  859个
  834个
  846个
  810个
......所以 875行丢失了 如果我从父项中删除LEFT JOIN "= 1 -- "SELECT IFNULL ( t4.ItemID, IFNULL(t3.ItemID, IFNULL(t2.ItemID, t1.ItemID))) AS ID, IFNULL(t4.ParentItemID, IFNULL(t3.ParentItemID, IFNULL(t2.ParentItemID, t1.ParentItemID))) as Parent, IFNULL(tp4.ItemNo, IFNULL(tp3.ItemNo, IFNULL(tp2.ItemNo, tp1.ItemNo))) AS ItemNo FROM ItemsParents AS t1 LEFT JOIN ItemsDB AS tP1 ON t1.ItemID = tP1.ID LEFT JOIN ItemsParents AS t2 ON t1.ItemID = 1 -- t2.ParentItemID LEFT JOIN ItemsDB AS tP2 ON t2.ItemID = tP2.ID LEFT JOIN ItemsParents AS t3 ON t2.ItemID = 1 -- t3.ParentItemID LEFT JOIN ItemsDB AS tP3 ON t3.ItemID = tP3.ID LEFT JOIN ItemsParents AS t4 -- t4.ParentItemID ON t3.ItemID = 1 LEFT JOIN ItemsDB AS tP4 ON t4.ItemID = tP4.ID WHERE t1.ParentItemID = ( SELECT ID FROM ItemsDB WHERE ItemNoInt = 359 ) - 评论原始条件):

{{1}}

...我从左连接表(822和875)返回正确的两行。

我搜索了左连接表中丢失行的情况,但似乎没有一个适用于这种情况。有什么想法吗?

此致

Libor的

1 个答案:

答案 0 :(得分:0)

不是答案,只是IDEA,我希望您已经要求在左连接中找到最后一行表格,

select LastRowofSubTable.* from tableMain
outer apply
(
    select top 1 * from tableSub
    where tableMain.id = tableSub.id
    order by tableSub.pk_id desc
)as LastRowofSubTable