Mysql query to get rows of a table as columns of another, with column names from third table

user210528

The real problem I'm trying to solve, is how to get all the clients from WHMCS database with all their custom fields. I thought I could use a query in phpmyadmin in order to finally get the result in a csv.

Short explanation of database scheme structure: WHMCS, has two extra tables (tblCustomFields and tblCustomFieldsValues) to facilitate custom fields created by the application users. For every new custom field created, the name and its id are stored in tblCustomFields. When a custom field in a client's profile is filled, the value is stored with the id of the client and the id of the field name in a row of tblCustomFieldsValues.

Simplified / Generic version of the problem

I'll try to describe a simplified generic version of the question which may apply to many similar situations.

Hypothesis

I have three tables:

+----------------------------------------------------+
|                     tblClients                     |
+----------------------------------------------------+
| id | company   | standard_field1 | standard_field2 |
+----+-----------+-----------------+-----------------+
| 1  | A company | abc             | yz              |
+----+-----------+-----------------+-----------------+
| 2  | B company | xyz             | foo             |
+----+-----------+-----------------+-----------------+
| 3  | C company | zyx             | bar             |
+----+-----------+-----------------+-----------------+


+--------------------------+
|      tblCustomFields     |
+--------------------------+
| id | fieldname           |
+----+---------------------+
| 1  | Custom Field Name 1 |
+----+---------------------+
| 2  | Custom Field Name 2 |
+----+---------------------+
| 3  | Custom Field Name 3 |
+----+---------------------+

+----------------------------------------------------+
|                tblCustomFieldsValues               |
+----------------------------------------------------+
|      relid      |      fieldid       |    value    |
| (corresponds to |   (corresponds to  |             |
|   a client id)  | a custom field id) |             |
+-----------------+--------------------+-------------+
| 1               | 1                  | any value   |
+-----------------+--------------------+-------------+
| 1               | 2                  | some value  |
+-----------------+--------------------+-------------+
| 1               | 3                  | field value |
+-----------------+--------------------+-------------+
| 2               | 1                  | data        |
+-----------------+--------------------+-------------+
| 2               | 2                  | whatever    |
+-----------------+--------------------+-------------+
| 2               | 3                  | anything    |
+-----------------+--------------------+-------------+
| 3               | 1                  | and so on   |
+-----------------+--------------------+-------------+
| 3               | 2                  | and on      |
+-----------------+--------------------+-------------+

Objective

I need the data of all the clients, exported from the database to a csv. Important: Every client should appear in only one line. The expected result should look similar to this:

+-----------------------------------------------------------------------------+
|       query result, clients with their custom fields as extra columns       |
+-----------------------------------------------------------------------------+
| id |  company  | standard | standard |  Custom   |   Custom   |   Custom    |
|    |           |  field1  |  field2  |   Field   |    Field   |    Field    |
|    |           |          |          |   Name 1  |   Name 2   |    Name 3   |
+----+-----------+----------+----------+-----------+------------+-------------+
| 1  | A company | abc      | yz       | any value | some value | field value |
+----+-----------+----------+----------+-----------+------------+-------------+
| 2  | B company | xyz      | foo      | data      | whatever   | anything    |
+----+-----------+----------+----------+-----------+------------+-------------+
| 3  | C company | zyx      | bar      | and so on | and on     |             |
+----+-----------+----------+----------+-----------+------------+-------------+

The idea

I thought that a solution would be to enter a query in phpmyadmin and then easily get the result in a csv.

The final question

What would be the mysql query to get all the clients with their custom fields in separate columns ? Is there a better way to reach the objective stated above?

If you have any ideas on how to rephrase the title or any part of the question in order to make it more clear, please comment!

Mohit Aggarwal

You can use the Pivot to get the expected output but as Mysql doesn't support pivot you have to use the case when clause. SQL query is as follows: Static SQL Query:

Select TB.*, TC.`standard_field1`, TC.`standard_field2`
from tblClients TC
Inner Join(
SELECT TBD.Id, TBD.company,
  Max(CASE WHEN (TBD.fieldname ='Custom Field Name 1') THEN TBD.value ELSE NULL END) AS 'Custom Field Name 1',
  Max(CASE WHEN (TBD.fieldname ='Custom Field Name 2') THEN TBD.value ELSE NULL END) AS 'Custom Field Name 2',
  Max(CASE WHEN (TBD.fieldname ='Custom Field Name 3') THEN TBD.value ELSE NULL END) AS 'Custom Field Name 3'
FROM(
Select TC.Id, TC.Company,
  TCF.fieldname, TCFV.Value
  from tblCustomFieldsValues TCFV
  Inner Join tblClients TC
  ON TCFV.relid = TC.ID
  Inner Join tblCustomFields TCF
  ON TCFV.fieldid = TCF.Id) TBD

 Group BY TBD.Id, TBD.company) TB
 On TB.Id = TC.Id

I am also providing the SQL fiddle link which will help you to get complete data along with output.

Dynamic SQl Query:

SET @sql = NULL;
SELECT 
  GROUP_CONCAT(DISTINCT
               CONCAT('Max(CASE WHEN (TBD.fieldname =''', UN.fieldname,
                      ''') THEN TBD.value ELSE NULL END) AS ''',UN.fieldname,''''))
    INTO @sql
    FROM (
      Select * from tblCustomFields) UN;

SET @sql =  CONCAT('Select TB.*, TC.`standard_field1`, TC.`standard_field2`
                    from tblClients TC
                    Inner Join(SELECT TBD.Id, TBD.company, ', @sql, ' 
                      FROM(
                        Select TC.Id, TC.Company,
                          TCF.fieldname, TCFV.Value
                          from tblCustomFieldsValues TCFV
                          Inner Join tblClients TC
                          ON TCFV.relid = TC.ID
                          Inner Join tblCustomFields TCF
                          ON TCFV.fieldid = TCF.Id) TBD

                         Group BY TBD.Id, TBD.company) TB On TB.Id = TC.Id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQL Fiddle Link

I hope this will help you.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

MySQL query with COUNT and join column from another table

From Dev

How to get 2 columns from one table and 2 rows as columns from other table in one row, in MySQL?

From Dev

How can i sum rows when a certain column value are equal from another table and insert them to a third table?

From Dev

MySQL - Get column names from table and display them (using PHP)

From Dev

Mysql Query for inserting from one table to another on Multiple conditions and columns

From Dev

Inserting rows in a table from another table using a third table

From Dev

mysql: select rows from another table as columns

From Dev

MYSQL Import Column from another table matching multiple columns

From Dev

SQL Query : Obtaining Rows where Columns A in Table A = Column A in Table B

From Dev

Fetch rows in MySQL which are not present in both columns from another table

From Dev

MYSQL query check if ID exist and copy column row values to another table related column names

From Dev

Get dynamic column names from another table for SQL Update

From Dev

MYSQL Query matching column names to rows in another table

From Dev

Sql Query to get column name from another table

From Dev

looping mysql query to get multiple rows of data from a table and insert into another table

From Dev

MySQL: Get the MIN value of a table from all columns & rows

From Dev

MySQL - Get column names from table and display them (using PHP)

From Dev

query to get column values based on values of another table i.e,one table values having as field names in another table

From Dev

Mysql Query for inserting from one table to another on Multiple conditions and columns

From Dev

MYSQL Import Column from another table matching multiple columns

From Dev

MySQL query to find if a value of one column in one table is between two values in two columns on another table

From Dev

Fetch rows in MySQL which are not present in both columns from another table

From Dev

How to get all columns from one table and only one column from another table with ID ? - MySql

From Dev

MYSQL/Query: How to make table rows into column

From Dev

Mysql - update column from another table data without reducing rows

From Dev

How to match a column result from query result to a table column value and get more columns from same table?

From Dev

SQL Query to compare two columns with one column from another table (and get two values)

From Dev

MySQL - Query For Rows With Updates Based On Another Table

From Dev

MySQL + Adjusting current query to get additional data from another table (per column)

Related Related

  1. 1

    MySQL query with COUNT and join column from another table

  2. 2

    How to get 2 columns from one table and 2 rows as columns from other table in one row, in MySQL?

  3. 3

    How can i sum rows when a certain column value are equal from another table and insert them to a third table?

  4. 4

    MySQL - Get column names from table and display them (using PHP)

  5. 5

    Mysql Query for inserting from one table to another on Multiple conditions and columns

  6. 6

    Inserting rows in a table from another table using a third table

  7. 7

    mysql: select rows from another table as columns

  8. 8

    MYSQL Import Column from another table matching multiple columns

  9. 9

    SQL Query : Obtaining Rows where Columns A in Table A = Column A in Table B

  10. 10

    Fetch rows in MySQL which are not present in both columns from another table

  11. 11

    MYSQL query check if ID exist and copy column row values to another table related column names

  12. 12

    Get dynamic column names from another table for SQL Update

  13. 13

    MYSQL Query matching column names to rows in another table

  14. 14

    Sql Query to get column name from another table

  15. 15

    looping mysql query to get multiple rows of data from a table and insert into another table

  16. 16

    MySQL: Get the MIN value of a table from all columns & rows

  17. 17

    MySQL - Get column names from table and display them (using PHP)

  18. 18

    query to get column values based on values of another table i.e,one table values having as field names in another table

  19. 19

    Mysql Query for inserting from one table to another on Multiple conditions and columns

  20. 20

    MYSQL Import Column from another table matching multiple columns

  21. 21

    MySQL query to find if a value of one column in one table is between two values in two columns on another table

  22. 22

    Fetch rows in MySQL which are not present in both columns from another table

  23. 23

    How to get all columns from one table and only one column from another table with ID ? - MySql

  24. 24

    MYSQL/Query: How to make table rows into column

  25. 25

    Mysql - update column from another table data without reducing rows

  26. 26

    How to match a column result from query result to a table column value and get more columns from same table?

  27. 27

    SQL Query to compare two columns with one column from another table (and get two values)

  28. 28

    MySQL - Query For Rows With Updates Based On Another Table

  29. 29

    MySQL + Adjusting current query to get additional data from another table (per column)

HotTag

Archive