使用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
答案 0 :(得分: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'
)
答案 1 :(得分: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