送上温暖的祝福。
我有一个包含大量数据的表,我需要除最后更新的数据之外的所有数据
Table
id - name - user_id - email
1 - abc - 1 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="49282b2a092c24282025672a2624" rel="noreferrer noopener nofollow">[email protected]</a>
2 - xyz - 2 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d8d9dae0c5cdc1c9cc8ec3cfcd" rel="noreferrer noopener nofollow">[email protected]</a>
3 - abc - 1 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e8898a8ba88d85898184c68b8785" rel="noreferrer noopener nofollow">[email protected]</a>
4 - pqr - 3 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7d7d6d5e7c2cac6cecb89c4c8ca" rel="noreferrer noopener nofollow">[email protected]</a>
5 - abc - 1 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4120232201242c20282d6f222e2c" rel="noreferrer noopener nofollow">[email protected]</a>
6 - pqr - 4 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93e3e2e1d3f6fef2faffbdf0fcfe" rel="noreferrer noopener nofollow">[email protected]</a>
现在我查询这样的东西
SELECT MAX(id),*
FROM `table`
GROUP BY user_id
ORDER BY id DESC
但它没有返回预期的输出。我的预期输出是
id - name - user_id - email
5 - abc - 1 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4322212003262e222a2f6d202c2e" rel="noreferrer noopener nofollow">[email protected]</a>
2 - xyz - 2 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d8d9dae0c5cdc1c9cc8ec3cfcd" rel="noreferrer noopener nofollow">[email protected]</a>
4 - pqr - 3 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5828292a183d35393134763b3735" rel="noreferrer noopener nofollow">[email protected]</a>
6 - pqr - 4 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7909080b391c14181015571a1614" rel="noreferrer noopener nofollow">[email protected]</a>
仅显示最后插入的数据。我引用 SQL select only rows with max value on a column [duplicate] 答案,但它并不用于获取所有数据。那么如何获取分组id时最后插入的所有数据呢?
最佳答案
您可以在同一个表上使用自联接来选择每个用户的最新行
SELECT a.*
FROM `table` a
JOIN (
SELECT user_id , MAX(id) id
FROM table
GROUP BY user_id
) b ON(a.user_id = b.user_id AND a.id = b.id)
ORDER BY a.id DESC
关于mysql - 使用 GROUP BY 时获取 desc 或最后插入的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51008389/