0

Im trying to write a query that pulls out data from a couple of other tables as columns in the query.

Here is the data:

User table

ID    ACCOUNT_ID    FIRST_NAME        LAST_NAME
1         1             Joe            SMITH
2         1             Bill           WALTERS
3         1             Bill           JOHNSON

User Fields Table

ID      ACCOUNT_ID     NAME
 1         1            CITY
 2         1            STATE
 3         2            EMPLOYEE_NUMBER
 4         3            MIDDLE_NAME

User Fields Data Table

ID    USER_FIELD_ID      USER_ID     DATA
 1         1               1         LINCOLN
 2         2               1         NEBRASKA

I would like a query something like:

SELECT FIRST_NAME, LAST_NAME FROM users WHERE ACCOUNT_ID=1

But I would like it to include CITY and STATE as columns, but these will be different based on the ACCOUNT_ID and the data in the User Fields table.

I'm thinking this might be accomplished with PIVOT, but I am having a hard time getting it to work. Thanks!

Jimmy Pelton
  • 11
  • 3
  • 16
  • Please show what you've tried. See http://stackoverflow.com/questions/7674786/mysql-pivot-table for examples of how to do pivot in MySQL. – Barmar Jun 21 '16 at 19:41
  • And see http://stackoverflow.com/questions/26665499/mysql-create-a-new-table-using-data-and-columns-from-three-tables/26665554#26665554 for how to join with an attribute-value table. – Barmar Jun 21 '16 at 19:42
  • Read this: http://modern-sql.com/use-case/pivot – Markus Winand Jun 22 '16 at 13:06

1 Answers1

1

using this code will act similar to a PIVOT. You would need to add a MAX(CASE) for each User Field type you want. Since it is using an Aggregate, you will only get one value from User Fields Data for each User Field

SELECT  u.FIRST_NAME, 
        u.LAST_NAME, 
        uf.CITY, 
        uf.STATE
FROM    users u
        LEFT JOIN (SELECT   uf.ACCOUNT_ID,
                            ufd.USER_ID,
                            MAX(CASE WHEN uf.NAME = 'CITY' THEN [DATA] END) AS CITY,
                            MAX(CASE WHEN uf.NAME = 'STATE' THEN [DATA] END) AS STATE
                   FROM     UserFields uf
                            JOIN UserFieldData ufd ON uf.ID = ufd.USER_FIELD_ID
                   GROUP BY uf.ACCOUNT_ID,
                            ufd.USER_ID
                  ) uf ON uf.USER_ID = u.ID
                          AND uf.ACCOUNT_ID = u.ACCOUNT_ID
WHERE   u.ACCOUNT_ID = 1
JamieD77
  • 13,796
  • 1
  • 17
  • 27