表AMySQL的左JOIN B表GROUP BY A.id而是爲了通過B.id
id(UNIQUE) name
1 tomato
2 potato
表B
id AID buy_date buy_money
6 1 2015-01-01 100
7 1 2015-02-02 200
我想選擇與過濾名全A的記錄,與最新的buy_date和buy_money像這樣:
A.id A.name B.buy_date B.buy_money
1 tomato 2015-02-02 200
2 potato NULL NULL
我該如何編寫SQL腳本?我曾嘗試過:
select A.id, A.name, MAX(B.buy_date)
from A left join B on A.id = B.AID
where A.name like '%to%'
Group by A.id
但是,這隻得到正確的buy_date,但沒有buy_money。這裏
'選擇一個。*,x.buy_date,x.buy_money從連接BX ON b.aid = a.id JOIN(SELECT助劑,MAX(購買日期)max_buy_date來自組B BY助劑)Y Y上.aid = x.aid AND y.max_buy_date = x.buy_date;' – Strawberry
@Strawberry有沒有簡單的方法沒有子查詢? – KKorange
是的。但它慢... https://dev.mysql.com/doc/refman/5.7/en/example-maximum-column-group-row.html – Strawberry