2011-10-15 49 views
0

這些都是(例如)表的引用加盟:MySQL的嵌套到嵌套的表中的字段

first: id  abc 

parent: id childid foo 
     1  0  -- no child 
     2  1  -- one child 

child: id abc bar 
     1 
     2 

last: id foo bar 

我想執行以下查詢:

SELECT 
    first.* 
,parent.* 
,child.* 
,last.* 

FROM  first -- actually some joins 

-- select exactly 1 `parent` row for each `first` row 
-- with an optional `child` row (or NULLs if child.id=0) 
LEFT JOIN (parent 
LEFT JOIN child ON child.id = parent.childid 
       AND child.abc = first.abc <== ERROR HERE 
     )  ON parent.childid = 0 
        OR child.id 


-- conditions referring to the parent,child rows 
LEFT JOIN last ON last.foo = parent.foo 
       AND last.bar = child.bar 

不幸的是MySQL不喜歡外部嵌套連接中的引用:
Unknown column 'first.abc' in 'on clause'

如果有人能幫我修復此類型,我會很高興o f查詢。

回答

1
  1. 丟掉那些括號!
  2. ON parent.childid = 0 OR child.id無效。使用ON parent.childid in (0, child.id)

它應該是這樣的:

... 
LEFT JOIN parent -- removed opening bracket 
LEFT JOIN child ON child.id = parent.childid 
       AND child.abc = first.abc 
       AND parent.childid = in (0, child.Id) -- removed closing bracket and used 'IN' 
... 
+0

謝謝,我試試這個對我真正的查詢。 – biziclop

+0

嗯,問題在於你的查詢會爲每個'第一'行添加多個父行。 – biziclop

+0

說實話,我認爲你的查詢具有可疑的價值。確實只需要一個父母是一件奇怪的事情。順便說一句,不止一個父母表示你有多對多,所以「父母」是錯誤的詞,但我只是將一個特殊的外鍵列分配給你的子表,其中有「第一父母」的關鍵無論如何),並用它來加入它。 – Bohemian

1

試試這個查詢,而不是:

SELECT first.*, parent.*, child.*, last.* 
FROM first 
LEFT JOIN parent ON parent.childid = 0 OR parent.childid IS NOT NULL 
LEFT JOIN child ON child.id = parent.childid AND child.abc = first.abc 
LEFT JOIN last ON last.foo = parent.foo AND last.bar = child.bar