MySQL correlated subquery in JOIN syntax

后端 未结 5 1854
深忆病人
深忆病人 2020-12-30 01:34

I would like to provide a WHERE condition on an inner query by specifying innertable.id = outertable.id. However, MySQL (5.0.45) reports \"Unknown column \'outertable.id\' i

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 02:07

    The answer to your question is no, it is not possible to reference correlation names as you are doing. The derived table is produced by your inner query before the outer query starts evaluating joins. So the correlation names like t, tp, and u are not available to the inner query.

    To solve this, I'd recommend using the same constant integer value in the inner query, and then join the derived table in the outer query using a real condition instead of 1=1.

    SELECT t.ticketid, u.userid, t.fullname, u.loginapi_userid, t.email,
      tp.subject, tp.contents, a.PhoneNumber, a.Location, a.Extension,
      a.BusinessUnit, a.Department
    FROM swtickets t
     INNER JOIN swticketposts tp ON (t.ticketid = tp.ticketid)
     INNER JOIN swusers u ON (t.userid = u.userid)
     LEFT OUTER JOIN (
      SELECT cfv.typeid,
        MIN(CASE cfv.customfieldid WHEN 1 THEN cfv.fieldvalue END) AS 'PhoneNumber',
        MIN(CASE cfv.customfieldid WHEN 3 THEN cfv.fieldvalue END) AS 'Location',
        MIN(CASE cfv.customfieldid WHEN 5 THEN cfv.fieldvalue END) AS 'Extension',
        MIN(CASE cfv.customfieldid WHEN 8 THEN cfv.fieldvalue END) AS 'BusinessUnit',
        MIN(CASE cfv.customfieldid WHEN 9 THEN cfv.fieldvalue END) AS 'Department'
      FROM swcustomfieldvalues cfv
      WHERE cfv.typeid = 2458
      GROUP BY cfv.typeid
      ) AS a ON (a.typeid = t.ticketid)
    WHERE t.ticketid = 2458;
    

提交回复
热议问题