我有两个与用户信息有关的表: 表1(用户)包含诸如id,用户名和电子邮件之类的列 表2(详细信息)包含诸如user_id,degree_name和degree的列 当我加入这两个表时,得到的结果是:
name degree_name degree
john doe Metric Science
john doe Fsc Engineering
john doe Bsc BSCS
herald Metric Science
Matt Metric Science
在以上记录中,“ john doe”重复了3次。什么不应该是预期的结果。 我想要的结果是,而且我知道可以通过使用find_in_set()实现:
0: {name: john doe
details: {0: {degree: "Science",degree_name: "Metric"}
1: {degree: "Fsc",degree_name: "Engineering "}
2: {degree: "Science",degree_name: "BSCS"}}}
1: {name: herald
details: {0: {degree: "Science",degree_name: "Metric"}}}
2: {name: Matt
details: {0: {degree: "Science",degree_name: "Metric"}}}
有人指导我进行正确的查询吗?
答案 0 :(得分:0)
您可以将group_concat用于学位和学位名称。例如。 :
SELECT name, group_concat(degree), group_concat(degree_name) FROM Table1,Table2 WHERE Table1.id=Table.User_id. GROUP BY Table1.id
它将为您为一个用户提供一行结果。
Jon Doe |公制,Fsc,Bsc |科学,工程学士。
答案 1 :(得分:0)
SELECT u.username, CONCAT('{ "array": [',
GROUP_CONCAT(CONCAT('{"degree_name": "',
d.degree_name,
'", "degree": "',
d.degree,
'"}'
) separator ','),
']}') As details
FROM details d
INNER JOIN users u
ON FIND_IN_SET(u.id, d.user_id) > 0
GROUP BY u.id;
此查询将提供预期的答案。在获取结果后,只需要一点点就可以对json解析记录。