我编写了一个mysql查询来使用nodejs api检索数据。一切正常,但我想改变数据格式。我的数据格式是:
"data": [
{
"Name": "faseeh tauheed,Muhammad Saeed,Farhan Khan",
"Email": "faseeh@gmail.com,saeed@gmail.com,farhan@gmail.com",
"Contact": "923158414969,923132347067,923471220797",
"Skill": "HTML",
"Experience": "36,72,48"
}
]
但我希望每个人的记录在一行中如下:
"faseeh tauheed", "faseeh@gmail.com", "923158414969", "HTML", "36"
我在数据中遇到歧义,所以我使用了MYSQL的GROUP_CONCAT()方法。 这是我的疑问:
SELECT GROUP_CONCAT(DISTINCT CONCAT(a.FirstName," ",a.LastName)) AS Name,
GROUP_CONCAT(DISTINCT b.Email) as Email, GROUP_CONCAT(DISTINCT a.Contact) as Contact,
GROUP_CONCAT(DISTINCT c.skillName) as Skill, GROUP_CONCAT(DISTINCT d.totalExperience)
AS Experience from applicant_personal_info a JOIN applicant b ON a.ApplicantID =
b.ApplicantID JOIN applicant_skills c ON a.ApplicantID = c.ApplicantID
JOIN applicant_professional_info d ON a.ApplicantID = d.ApplicantID
WHERE c.skillName = 'HTML'
答案 0 :(得分:1)
最好不要连接任何数据。然后,您将拥有可以轻松使用的单独行。我也解散了FirstName和Name,因为稍后会更容易使用 - 但如果你真的需要,你可以保持这个连续
SELECT a.FirstName AS FirstName,
a.LastName AS Name, -- or CONCAT(a.FirstName," ",a.LastName) as Name
b.Email AS Email,
a.Contact AS Contact,
c.skillName AS Skill,
d.totalExperience AS Experience
FROM applicant_personal_info a
JOIN applicant b ON a.ApplicantID = b.ApplicantID
JOIN applicant_skills c ON a.ApplicantID = c.ApplicantID
JOIN applicant_professional_info d ON a.ApplicantID = d.ApplicantID
WHERE c.skillName = 'HTML'
你会得到:
"data": [
{
"FirsName": "faseeh",
"Name": "tauheed",
"Email": "faseeh@gmail.com",
"Contact": "923158414969",
"Skill": "HTML",
"Experience": "36"
},
{
"FirstName": "Muhammad",
"Name": "Saeed",
"Email": "saeed@gmail.com",
"Contact": "923132347067",
"Skill": "HTML",
"Experience": "72"
},
{
"FirstName": "Farhan",
"Name": "Khan",
"Email": "farhan@gmail.com",
"Contact": "923471220797",
"Skill": "HTML",
"Experience": "48"
}
]
如果您只需要获取第一行数据,请在查询末尾添加以下行:
LIMIT 1;
-
最后但并非最不重要的一点是,如果出于某种原因肯定需要使用这些CONCAT,您可以将这些数据与节点分开。你的SQL语句已经足够复杂了,即使你通过过度复杂的方式正确地完成它,如果需要的话,在几个月内维护和改变将是一场噩梦。
- 编辑:
SELECT CONCAT('"',
a.FirstName , '", "',
a.LastName , '", "',
b.Email , '", "',
a.Contact , '", "',
c.skillName , '", "',
d.totalExperience , '"') as user
FROM applicant_personal_info a
JOIN applicant b ON a.ApplicantID = b.ApplicantID
JOIN applicant_skills c ON a.ApplicantID = c.ApplicantID
JOIN applicant_professional_info d ON a.ApplicantID = d.ApplicantID
WHERE c.skillName = 'HTML'
应该给:
"data": [
{
"User": "\"faseeh\", \"tauheed\", \"faseeh@gmail.com\", \"923158414969", \"HTML\", \"36\""
},
{
... with all the other users in the same format
]
\"这里仅代表双引号可能会在你的json中转义的事实