MySQL将具有相同ID的多行合并到一行

时间:2017-05-19 09:03:44

标签: mysql sql database rows

我有一个包含多个相同ID的行的表我想要找出一个SQL查询,它允许我将相关的字段编号和值放入一个单独的列中;对于值1.3,将创建一个名为first的新列,1.6将是姓氏,依此类推。我想尝试将所有信息放入一行,因此对于lead_id值为79的每一行,只有一行而不是9行。我不确定这是否可能?我已经预览了下面的数据库结构,试图表明我的意思。

ID   lead_id   field_number   Value

1       79         1.3        John
2       79         1.6        Doe
3       79          2         johndoe@example.com
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         janedoe@example.com
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

非常感谢任何帮助!

1 个答案:

答案 0 :(得分: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