MySQL嵌套连接,引用了未连接的表字段

时间:2011-10-15 21:22:17

标签: mysql sql join

这些是(示例)表:

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'

如果有人可以帮我修复此类查询,我会很高兴。

2 个答案:

答案 0 :(得分:1)

  1. 丢掉这些括号!
  2. ON parent.childid = 0 OR child.id无效。使用ON parent.childid in (0, child.id)
  3. 它应该是这样的:

    ...
    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'
    ...   
    

答案 1 :(得分: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