2017-01-11 218 views
0

我有一些麻煩,下面的問題,會告訴你我有什麼,我想要什麼,我都試過...選擇子查詢子表

我想要什麼:我有一個家長和孩子表中,母公司是

訪問

和子表是

評估

,有一個在兩者之間定義一對多的關係,請參見下面的表結構:

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做到這一點,並將數據物理存儲在表中,但我寧願不走這條路。

我已經嘗試在第一個選擇語句運行子查詢,但沒有甚至接近第二選擇語句。

我一直在使用這個〔實施例中發現也試過: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例如放置第二個SELECT語句,但通過查找where 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

我也已經嘗試(SELECT GROUP_CONCAT('scope' SEPARATOR '')從評估LEFT OUTER JOIN評估ON visits.VisitPk = assessments.VisitFk GROUP連接兩個表和組)作爲Scope, – jaykay79

+0

和group_concat('Scope')作爲來自評估的標準,其中visits.VisitPk = assess.VisitFk, – jaykay79

回答

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