简体   繁体   中英

I am trying to get data from row to match into defined columns

Using PHP / MySQL

I have two tables one is customers the other is cust_data

there is a field that matches the two it is ListID

Now inside the cust_data table the data is listed as cust_data

columns:

ListID  DataName  DataValue
 1      type      something
 1      Region    something

customers columns:

ListID Name Address City State Zip Phone

I want to get the results as

Name Address City State Zip Phone Type Region
SELECT customers.*, data_type.DataValue AS Type, data_region.DataValue AS Region
FROM   customers
  JOIN cust_data AS data_type ON (
         data_type.ListID   = customers.List_ID
     AND data_type.DataName = 'Type'
  )
  JOIN cust_data AS data_region ON (
         data_region.ListID   = customers.List_ID
     AND data_region.DataName = 'Region'
  )

You can do it using a group query. The fact that you can group by ListID to get a single row makes this relatively straightforward-- just select conditionally and alias the DataValue field as needed:

SELECT c.Name, c.Address, c.City, c.State, c.Zip, c.Phone,
    MAX (CASE WHEN d.DataName = 'type' THEN DataValue ELSE NULL END) AS  `Type`,
    MAX (CASE WHEN d.DataName = 'Region' THEN DataValue ELSE NULL END) AS  `Region`
FROM customers c, cust_data d
WHERE c.ListID = d.ListID
GROUP BY c.ListID, c.Name, c.Address, c.City, c.State, c.Zip, c.Phone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM