获取具有最大 id 的行
Get a row which has the maximum id
简单来说就是问题,第 1 个必须与第 2 个 table 相连,其中记录是最新的。所以,我使用了一种使用函数 MAX()
的方法
目前我有 2 个 table。
匹配
matches_payments
|
现在我想在 matches_payments
上使用 MAX(id) 将第二个 table 加入第一个
想要的结果
但由于 greatest-n-per-group
问题,我没有得到想要的结果。
查询
SELECT matches.id, mp.*
FROM matches
LEFT JOIN (SELECT
MAX(id) AS id,
match_id
paymentStatus
FROM matches_payments
GROUP BY match_id) AS mp ON mp.id = matches.id;
由于以下原因未产生预期结果:Whosebug Question
When using this feature, all rows in each group should have the same values for the columns that are ommitted from the GROUP BY part. The server is free to return any value from the group, so the results are indeterminate unless all values are the same.
FROM MySQL Dev
PS :我知道 table 的设计很糟糕。这不是我的工作,因为最后一个开发人员做了那些。
您需要两个联接。您需要 matches_payments
table 的 self-join 来获取每个 match_id
具有最高 ID 的行,如 SQL Select only rows with Max Value on a Column 所示。然后你 LEFT JOIN
这个到 matches
结合两个 tables:
SELECT m.*, mp.paymentStatus, mp.paymentAmount
FROM matches AS m
LEFT JOIN (
SELECT mp1.*
FROM matches_payments AS mp1
JOIN (SELECT match_id, MAX(id) AS id
FROM matches_payments
GROUP BY match_id) AS mp2
ON mp1.match_id = mp2.match_id AND mp1.id = mp2.id
) AS mp ON mp.match_id = m.id
简单来说就是问题,第 1 个必须与第 2 个 table 相连,其中记录是最新的。所以,我使用了一种使用函数 MAX()
的方法目前我有 2 个 table。
匹配
matches_payments
现在我想在 matches_payments
想要的结果
但由于 greatest-n-per-group
问题,我没有得到想要的结果。
查询
SELECT matches.id, mp.*
FROM matches
LEFT JOIN (SELECT
MAX(id) AS id,
match_id
paymentStatus
FROM matches_payments
GROUP BY match_id) AS mp ON mp.id = matches.id;
由于以下原因未产生预期结果:Whosebug Question
When using this feature, all rows in each group should have the same values for the columns that are ommitted from the GROUP BY part. The server is free to return any value from the group, so the results are indeterminate unless all values are the same. FROM MySQL Dev
PS :我知道 table 的设计很糟糕。这不是我的工作,因为最后一个开发人员做了那些。
您需要两个联接。您需要 matches_payments
table 的 self-join 来获取每个 match_id
具有最高 ID 的行,如 SQL Select only rows with Max Value on a Column 所示。然后你 LEFT JOIN
这个到 matches
结合两个 tables:
SELECT m.*, mp.paymentStatus, mp.paymentAmount
FROM matches AS m
LEFT JOIN (
SELECT mp1.*
FROM matches_payments AS mp1
JOIN (SELECT match_id, MAX(id) AS id
FROM matches_payments
GROUP BY match_id) AS mp2
ON mp1.match_id = mp2.match_id AND mp1.id = mp2.id
) AS mp ON mp.match_id = m.id