2017-05-19 142 views
3

我有一個具有多個相同ID的行的表我想弄清楚一個SQL查詢,它允許我將相關的字段號和值放入單獨的列中例如;對於值1.3,將創建一個新的列,第一個將被創建,1.6將是姓,依此類推。我想試圖將所有信息都放入一行,因此對於lead_id值爲79的每一行,只有一行而不是9行。我不確定這是否可能?我已經在下面預覽了數據庫結構,試圖展示我的意思。MySQL將具有相同ID的多個行合併到一行中

ID lead_id field_number Value 

1  79   1.3  John 
2  79   1.6  Doe 
3  79   2   j[email protected] 
4  79   6   POSTCODE 
5  79   3   01332 1234567 
6  79   4   DATE OF BIRTH 
7  79   7   APPLICATION ID 
8  79   9   CITY NAME 
9  79   5   RESUME URL 
10  80   1.3  Jane 
11  80   1.6  Doe 
12  80   2   [email protected] 
13  80   6   POSTCODE 
14  80   3   01332 1234567 
15  80   4   DATE OF BIRTH 
16  80   7   APPLICATION ID 
17  80   9   CITY NAME 
18  80   5   RESUME URL 

任何幫助將不勝感激!

回答

2

您可以使用多個SELECT查詢此,例如:

SELECT t.lead_id, 
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 1.3) as 'first name', 
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 1.6) as 'last name', 
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 2) as 'email', 
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 6) as 'post code', 
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 3) as 'phone', 
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 4) as 'dob' 
FROM table t 

您可以添加更多的列多SELECT秒。

+0

謝謝我結束了使用GROUP_CONCAT(IF('field_number' = 2,VALUE,NULL))作爲'電子郵件',感謝您的幫助,雖然 –

相關問題