2017-05-08 129 views
-1

Photos TableSQL - 查詢字符串請求

Projects Table

​​是Projects.Pr_ID

外鍵我需要Project.Name,Project.Pro_ID,COUNT Photo.PID每個Photo.Pr_ID和該項目的TOP 1 Photos.P_Path。我將User_Id作爲查詢的條件參數。結果應該是GROUP BY Projects.Pro_ID以及。

回答

0
SELECT Project.Name, Project.Pro_ID, sub.P_Path, COUNT(Photo.PID) 
FROM Project 
JOIN Photo ON Project.Pro_ID = Photo.Pro_ID 
JOIN (SELECT P_Path FROM Projects GROUP BY Pro_ID, P_Path) sub 
ON sub.Pro_ID = Project.Pro_ID 
GROUP BY Projects.Pro_ID, Project.Name, sub.P_Path 

這應該讓你至少相對接近你正在尋找的結果。這假設所有項目的P_Path值都是重複的。儘可能不要在子查詢中執行SELECT TOP 1。

0

@Jacob H 我做了必要的修改。

SELECT Projects.Name, Projects.Pro_ID, sub.P_Path, COUNT(Photos.PID) 
FROM Projects 
JOIN Photos ON Projects.Pro_ID = Photos.Pr_ID 
JOIN (SELECT Pr_ID,P_Path FROM Photos GROUP BY Pr_ID, P_Path) sub 
ON sub.Pr_ID = Projects.Pro_ID 
GROUP BY Projects.Pro_ID, Projects.Name, sub.P_Path 

但結果顯示我經常使用Projects.Pro_ID。最後,我只需要獲得一次項目ID。