How can I use rows in a lookup table as columns in a MySQL query?

Posted by TomH on Stack Overflow See other posts from Stack Overflow or by TomH
Published on 2010-05-12T13:47:07Z Indexed on 2010/05/12 14:04 UTC
Read the original article Hit count: 177

Filed under:

I'm trying to build a MySQL query that uses the rows in a lookup table as the columns in my result set.

LookupTable

id  |  AnalysisString
1   |  color
2   |  size
3   |  weight
4   |  speed

ScoreTable

id  |  lookupID | score | customerID
  1 |      1    |   A   |     1
  2 |      2    |   C   |     1 
  3 |      4    |   B   |     1 
  4 |      2    |   A   |     2
  5 |      3    |   A   |     2
  6 |      1    |   A   |     3 
  7 |      2    |   F   |     3

I'd like a query that would use the relevant lookupTable rows as columns in a query so that I can get a result like this:

customerID |  color  | size  | weight  | speed
     1          A        C                 D
     2                   A        A    
     3          A        F

The kicker of the problem is that there may be additional rows added to the LookupTable and the query should be dynamic and not have the Lookup IDs hardcoded. That is, this will work:

SELECT st.customerID, 
(SELECT st1.score FROM ScoreTable st1 WHERE lookupID=1 AND st.customerID = st1.customerID) AS color,
(SELECT st1.score FROM ScoreTable st1 WHERE lookupID=2 AND st.customerID = st1.customerID) AS size,
(SELECT st1.score FROM ScoreTable st1 WHERE lookupID=3 AND st.customerID = st1.customerID) AS weight,
(SELECT st1.score FROM ScoreTable st1 WHERE lookupID=4 AND st.customerID = st1.customerID) AS speed
FROM ScoreTable st
GROUP BY st.customerID

Until there is a fifth row added to the LookupTable . . .

Perhaps I'm breaking the whole relational model and will have to resolve this in the backend PHP code?

Thanks for pointers/guidance.

tom

© Stack Overflow or respective owner

Related posts about mysql-query