MySQL correlated subquery in JOIN syntax

后端 未结 5 1853
深忆病人
深忆病人 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

    You're using the Entity-Attribute-Value design, and there's ultimately no way to make this scalable if you try to generate conventional result sets. Don't try to do this in one query.

    Instead, query your normalized tables first:

    SELECT t.ticketid, u.userid, t.fullname, u.loginapi_userid, t.email, 
      tp.subject, tp.contents
    FROM swtickets t
     INNER JOIN swticketposts tp ON (t.ticketid = tp.ticketid)
     INNER JOIN swusers u ON (t.userid = u.userid)
    WHERE t.ticketid = 2458;
    

    Then query your custom fields, with the result on multiple rows of the result set:

    SELECT cfv.customfieldid, cfv.fieldvalue
    FROM swcustomfieldvalues cfv
    WHERE cfv.typeid = 2458;
    

    You'll get multiple rows in the result set, one row for each custom field:

    +---------------+--------------+
    | customfieldid | fieldvalue   |
    +---------------+--------------+
    |             1 | 415-555-1234 |
    |             3 | Third office |
    |             5 | 123          |
    |             8 | Support      |
    |             9 | Engineering  |
    +---------------+--------------+
    

    You then need to write application code to map the result-set fields to the application object fields, in a loop.

    Using an Entity-Attribute-Value table in this way is more scalable both in terms of performance and code maintenance.

提交回复
热议问题