列出组查询中的 id
我想为每个具有唯一金额
、操作
、月份
和费用
的数据集群返回一行> 对于给定的 id。
表格如下:
我几乎可以得到我想要的东西
SELECT amount, operation, months, fee, plan_id
FROM promo_discounts
WHERE promo_id = 1
GROUP BY amount, operation, months, fee
Which will get:
但请注意,当我希望它返回诸如 1 之类的内容时,它只返回一个
plan_id
, 2, 3
是这可能吗?
I want to return a row for each cluster of data that has a unique amount
, operation
, months
, and fee
for a given id.
Table is as follows:
I can almost get what I want with
SELECT amount, operation, months, fee, plan_id
FROM promo_discounts
WHERE promo_id = 1
GROUP BY amount, operation, months, fee
Which will get:
But notice it only returns one plan_id
when I want it to return something like 1, 2, 3
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
GROUP_CONCAT
但请注意,默认最大长度为 1024,因此如果您使用大型表执行此操作,则可能会出现截断值...
You could use
GROUP_CONCAT
Beware though, that the default maximum length is 1024, so if you're doing this with a large table, you could have truncated values...
看看 group_concat()< /a> 函数。
SELECT *, GROUP_CONCAT(id SEPARATOR ",") AS grouped_ids FROM 表
Have a look at the group_concat() function.
SELECT *, GROUP_CONCAT(id SEPARATOR ",") AS grouped_ids FROM table
如果您需要动态的东西,我不会推荐 GROUP_CONCAT。
GROUP_CONCAT 有限制。
您可以做的是使用临时表,您可以先选择其中的所有行,然后可以获得分组结果。
要获取 ID,您可以循环组并使用以所有组为条件的 WHERE 子句从临时表中进行选择。
我知道这对于这样的事情来说可能有点太复杂了,但我觉得如果你真的需要跟踪 ID,这是一个很好的解决方案。
I wouldn't recommend GROUP_CONCAT, if you need something dynamic.
GROUP_CONCAT has a limit.
What you could do is use a temp table where you can select all the rows there first, then you can get your grouped results.
To get the IDs you can loop the groups and select from the temp table with a WHERE clause that has all the groups as condition.
I understand it might be a little bit too complicated for such thing but I sounds to me that it is a good solution if you really need to keep track of the IDs.
在处理这个问题时,我想到的是将
group by
结果与组字段上的同一个表连接起来。请注意,两个选择中的WHERE
语句是相同的现在您可以使用结果来获得您想要的结果
What I came up with when dealing with this problem, is to join the
group by
result with the same table on the fields of the group. Notice that theWHERE
statement is the same in both selectsNow you can play with the result to get exactly what you want