我在以下问题上遇到了一些麻烦,会告诉你我有什么,我想要什么以及我尝试过什么......
我想要的是:我有一个父表和子表,父表是
访问
,子表是
评估
,两者之间定义了一对多的关系,见下面的表结构:
SELECT
VisitPk, (Primary Key)
ClientFk,
ClientSiteFk,
AssessorFk,
VisitStartDate,
VisitEndDate,
CONCAT(MONTHNAME(TargetDate), ' ', YEAR(TargetDate)) AS TargetMonth,
Duration,
VisitStatus,
TargetDate,
`Long`,
Lat,
VisitPlanRequired,
VisitPlanIssued,
VisitPlanStatus,
VisitPlanAttachment,
DATE_SUB(VisitStartDate, INTERVAL 1 Month) AS VisitPlanDue,
Overnight,
YEAR(TargetDate) AS `Year`
FROM visits
ORDER BY YEAR(TargetDate) DESC, TargetDate, VisitStartDate
和
SELECT
assessments.AssessmentPk, (Foreign Key)
assessments.VisitFk,
assessments.`Scope`,
FROM assessments
我需要的是将一个字段放入评估表中,以便它从访问表中查找所有范围,然后对它们进行分组。 E.G是访问pk 1有两个条目3个子记录,1,2和3,id喜欢使用concat / implode函数在父表中将其显示为1,2,3。
我可以用PHP做到这一点并将数据物理存储在表中,但我宁愿不沿着这条路走下去。
我已尝试在第一个select语句中使用第二个select语句来运行子查询但是甚至没有接近。
我也尝试过使用这个例子:Can I concatenate multiple MySQL rows into one field?,例如:
SELECT person_id, GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies GROUP BY person_id
最终,我需要的是有人告诉我如何使用上面的group_contact示例放置第二个选择语句,但是查找子表,其中assessmentfk = assessmentpk。
类似于:
SELECT
VisitPk, (Primary Key)
ClientFk,
ClientSiteFk,
**CONCAT(SELECT `scope` from assessments LEFT OUTER JOIN assessments ON visits.VisitPk = assessments.VisitFk) as `Scope`**
AssessorFk,
VisitStartDate,
VisitEndDate,
CONCAT(MONTHNAME(TargetDate), ' ', YEAR(TargetDate)) AS TargetMonth,
Duration,
VisitStatus,
TargetDate,
`Long`,
Lat,
VisitPlanRequired,
VisitPlanIssued,
VisitPlanStatus,
VisitPlanAttachment,
DATE_SUB(VisitStartDate, INTERVAL 1 Month) AS VisitPlanDue,
Overnight,
YEAR(TargetDate) AS `Year`
FROM visits
ORDER BY YEAR(TargetDate) DESC, TargetDate, VisitStartDate
我希望这是有道理的,有人可以提供帮助,这远远超出了我过去所做的任何事情,所以提前道歉。
答案 0 :(得分:0)
尝试两个表的内连接和
分组 SELECT
VisitPk, ClientFk, ClientSiteFk,AssessorFk,VisitStartDate, VisitEndDate,
GROUP_CONCAT(a.scope, ',') as scopes
CONCAT(MONTHNAME(TargetDate), ' ', YEAR(TargetDate)) AS TargetMonth,
Duration,VisitStatus,TargetDate,`Long`,Lat,VisitPlanRequired,
VisitPlanIssued,VisitPlanStatus,VisitPlanAttachment,
DATE_SUB(VisitStartDate, INTERVAL 1 Month) AS VisitPlanDue,
Overnight,YEAR(TargetDate) AS `Year`
FROM visits v
INNER JOIN assessments a
ON v.VisitPk = a. VisitFk
GROUP BY v.VisitPk
ORDER BY YEAR(TargetDate) DESC, TargetDate, VisitStartDate