2

使用 PHP/MySQL

我有两张桌子一张是customers另一张是cust_data

有一个与两者相匹配的字段ListID

现在在cust_data表格内,数据被列为cust_data

列:

ListID  DataName  DataValue
 1      type      something
 1      Region    something

客户栏:

ListID Name Address City State Zip Phone

我想得到结果

Name Address City State Zip Phone Type Region
4

2 回答 2

1
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'
  )
于 2012-05-16T16:48:41.447 回答
0

您可以使用组查询来完成。您可以按 ListID 分组以获得单行这一事实使得这相对简单——只需有条件地选择并根据需要为DataValue字段设置别名:

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
于 2012-05-16T16:49:26.483 回答