gpt4 book ai didi

mysql - 在按 group by 子句分组的每个组中仅选择 3 个具有 uniq 属性的第一个加入的项目

转载 作者:行者123 更新时间:2023-11-29 02:33:30 25 4
gpt4 key购买 nike

我有简单的 sql:

SELECT foos.*, bars.* FROM foos 
LEFT JOIN bars ON bars.foo_id = foos.id
WHERE foos.id = 1;

=>

+------------------------------------+
| foos.id | bars.id | bars.author_id |
+------------------------------------+
| 1 | 1 | 10 |
| 1 | 3 | 10 |
| 1 | 5 | 3 |
| 1 | 6 | 10 |
| 1 | 7 | 10 |
| 1 | 8 | 10 |
| 1 | 44 | 11 |
| 1 | 32 | 10 |
+------------------------------------+

现在我需要返回的不是所有连接的 bars,而是每个 bars.author_id 的前三个(切片),因此它可以有效地返回类似这样的东西

+------------------------------------+
| foos.id | bars.id | bars.author_id |
+------------------------------------+
| 1 | 1 | 10 |
| 1 | 3 | 10 |
| 1 | 5 | 3 |
| 1 | 6 | 10 |
| 1 | 44 | 11 |
+------------------------------------+

最佳答案

我有一个很好的解决方案:

For, selecting 1st 3 record within each group 
1) sorting the results asc/desc by applying `order by bars.id` within group_concat()
2) limiting the records by passing the 3rd parameter as the records to limit to SUBSTRING_INDEX(str,'match str','no of records to limit')

SELECT foos.id,
SUBSTRING_INDEX(GROUP_CONCAT(bars.id
order by bars.id),',',3),
bars.author_id

FROM foos LEFT JOIN bars ON bars.foo_id = foos.id

WHERE foos.id = 1
GROUP BY bars.author_id

结果是:

+------------------------------------+
| foos.id | bars.id | bars.author_id |
+------------------------------------+
| 1 | 1,3,6 | 10 |
| 1 | 5 | 3 |
| 1 | 44 | 11 |
+------------------------------------+

稍后,在应用程序端,您可以通过 ',' 分解它并使用它。

关于mysql - 在按 group by 子句分组的每个组中仅选择 3 个具有 uniq 属性的第一个加入的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9017689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com