可能對請求和員工進行另一次連接。
事情是這樣的: -
SELECT T.*, ER2.SEN, ER2.BIR, requestcnt
FROM tours T
LEFT OUTER JOIN
(
SELECT R.tourid, count(R.requestid) AS requestcnt, MIN(E.SEN) AS SEN
FROM requests R
INNER JOIN employees E ON E.employeeid = R.employeeid
WHERE Funktion = 'XY'
GROUP by R.tourid
) ER
ON ER.tourid = U.tourid
LEFT OUTER JOIN
(
SELECT R.tourid, E.SEN, MIN(E.BIR) AS BIR
FROM requests R
INNER JOIN employees E ON E.employeeid = R.employeeid
WHERE Funktion = 'XY'
GROUP by R.tourid, E.SEN
) ER2
ON ER2.tourid = U.tourid
AND ER.SEN = ER2.SEN
編輯 - 對於修訂後的要求
獲取任何東西的3是尷尬的,因爲你不能真正使用MIN/MAX功能得到它(用很多努力,你可以通過使用它們來找到並排除min,然後再用這個結果等等)。對於連接的子查詢,您無法輕鬆使用限制,因爲它可以處理查詢的整體結果,而不是每個組。
2種方式我可以想到我的頭頂。首先將一個序列號添加到子查詢中,該子查詢將按照資歷順序得到結果,這將重新設置三元組更改。
像這樣(未測試): -
SELECT T.*, ER2.SEN, ER2.BIR, requestcnt
FROM tours T
LEFT OUTER JOIN
(
SELECT R.tourid, count(R.requestid) AS requestcnt
FROM requests R
INNER JOIN employees E ON E.employeeid = R.employeeid
WHERE Funktion = 'XY'
GROUP by R.tourid
) ER
ON ER.tourid = T.tourid
LEFT OUTER JOIN
(
SELECT R.tourid, E.employeeid, E.SEN, E.BIR, @seq:=IF([email protected], @seq+1, 1) AS seq
FROM requests R
INNER JOIN employees E ON E.employeeid = R.employeeid
CROSS JOIN (SELECT @seq:=0, @tourid:=0)
WHERE Funktion = 'XY'
ORDER BY R.tourid, E.SEN, E.BIR, E.employeeid
) ER2
ON ER2.tourid = T.tourid
AND ER2.seq = 3
另一種方法是使用相關子查詢的SELECT。這可能會顯着放慢的行數返回的增加: -
SELECT T.*,
(
SELECT E.SEN
FROM requests R
INNER JOIN employees E ON E.employeeid = R.employeeid
WHERE Funktion = 'XY'
AND R.tourid = T.tourid
ORDER BY E.SEN, E.BIR
LIMIT 3,1
),
(
SELECT E.BIR
FROM requests R
INNER JOIN employees E ON E.employeeid = R.employeeid
WHERE Funktion = 'XY'
AND R.tourid = T.tourid
ORDER BY E.SEN, E.BIR
LIMIT 3,1
),
requestcnt
FROM tours T
LEFT OUTER JOIN
(
SELECT R.tourid, count(R.requestid) AS requestcnt
FROM requests R
INNER JOIN employees E ON E.employeeid = R.employeeid
WHERE Funktion = 'XY'
GROUP by R.tourid
) ER
ON ER.tourid = T.tourid
或可能在WHERE子句中(同樣未測試)
SELECT T.*, EM.SEN, EM.BIR, EM.employeeid,
requestcnt
FROM tours T
CROSS JOIN employees EM
LEFT OUTER JOIN
(
SELECT R.tourid, count(R.requestid) AS requestcnt
FROM requests R
INNER JOIN employees E ON E.employeeid = R.employeeid
WHERE Funktion = 'XY'
GROUP by R.tourid
) ER
ON ER.tourid = T.tourid
WHERE EM.employeeid =
(
SELECT E.employeeid
FROM requests R
INNER JOIN employees E ON E.employeeid = R.employeeid
WHERE Funktion = 'XY'
AND R.tourid = T.tourid
ORDER BY E.SEN, E.BIR
LIMIT 3,1
)
請樣本數據,預期的效果編輯你的問題,並解釋您的查詢無法正常工作的原因。 –