![](/img/trans.png)
[英]MySql PDO - How to fetch “newest rows from group” when using GROUP BY, ORDER BY and INNER JOIN?
[英]Data inconsistent when using group by and min clauses with inner join
我正在嘗試從表中獲取基於開始時間的即將發生的事件。 讓我們假設以下內容:實際上,我們正在聯接表。 在表中,Locationid是主鍵。 我們正在加入另一個表格以獲取場地名稱。 您可能認為我們有冗余數據,但沒有。 用戶在不同的日期訪問相同的場地。
現在我只想顯示即將到來的計划,即
locationid 2511和2515
這是我正在嘗試的查詢
SELECT B.`VenueID` ,
A.rather_to_be_flying_now,
A.my_favorite,
A.Locationid,
MIN( A.start ) ,
MIN( A.end )
FROM tbl_userselectedlocations A
INNER JOIN tbl_Flyingapp_Venue B ON A.VenueID = B.VenueID
WHERE A.Pilotid = '709'
GROUP BY `VenueID`
ORDER BY A.my_favorite DESC , A.start
但是在這一點上我得到了不正確的數據
Locationid = 順序分別為2511和2515,而不是2514和2516
查詢中有什么問題嗎?
曾嘗試內部查詢。 這里不使用INNER JOIN ,但是結果值不同。
SELECT A.Locationid, MIN(A.start), MIN(A.end)
FROM tbl_userselectedlocations A
WHERE A.Pilotid = '709'
group by VenueID
ORDER BY A.my_favorite DESC , A.start
嘗試使用子查詢為每個場所找到所需的開始時間,然后使用會場ID的值通過自我連接從該行中查找其余信息,然后開始:
SELECT B.VenueID, A.rather_bo_be_flying_now, A.my_favorite,
A.Locationid, A.start, A.end
FROM (SELECT venueID, MIN(start) AS start
FROM tbl_userselectedlocations
GROUP BY venueID) AS Z
INNER JOIN tbl_userselectedlocations A
ON A.VenueID = Z.VenueID AND A.start = Z.start
INNER JOIN tbl_Flyingapp_Venue B
ON A.VenueID = B.VenueID
WHERE A.Pilotid = '709'
ORDER BY A.My_favorite DESC, A.start
您可能首先需要一個子選擇:
SELECT C.VenueID ,
A.rather_to_be_flying_now,
A.my_favorite ,
A.Locationid ,
C.STARTP ,
C.ENDP
FROM
(
SELECT D.VenueID ,
MIN( D.start ) AS STARTP ,
MIN( D.end ) AS ENDP
FROM tbl_userselectedlocations D
WHERE D.Pilotid = '709'
GROUP BY `VenueID`
) C
INNER JOIN tbl_userselectedlocations A
ON A.VenueID = C.VenueID
INNER JOIN tbl_Flyingapp_Venue B
ON A.VenueID = B.VenueID
ORDER BY A.my_favorite DESC ,
C.STARTP
這是我使用的查詢,
$query="select distinct(`VenueID`),MIN(start) from tbl_userselectedlocations
where `Pilotid` = '709' group by `VenueID` order by `my_favorite` DESC ,start";
在這里循環
select * from tbl_userselectedlocations
where VenueID = '$row[0]' and start='$row[1]' and Pilotid='709'";
這給出了結果,但是如果我有以下記錄
MIN(start)
將只返回2511的locationid,但我需要將2514顯示為即將推出的計划。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.