gpt4 book ai didi

如果已选择 id,则 MySQL SELECT 递增计数器

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

我有一个非常简单的 MySQL 表,其结构如下:

id   | customer_id |  name  | address
-------------------------------
1 | 1 | John | 123 street
2 | 2 | Jane | 456 lane
3 | 1 | John | 789 square
4 | 1 | John | 000 street
5 | 3 | Paul | 666 hell

每个客户可以有多个地址,我想选择所有地址,每个 ID 都有一个递增的计数器,例如:

id   | customer_id |  address   |    count_by_id
----------------------------------------------------
1 | 1 | 123 street | John's address #1
2 | 2 | 456 lane | Jane's address #1
3 | 1 | 789 square | John's address #2
4 | 1 | 000 street | John's address #3
5 | 3 | 666 hell | Paul's address #1

我该如何继续?

最佳答案

SELECT x.*
, COUNT(*) rank
FROM customer_address x
JOIN customer_address y
ON y.customer_id = x.customer_id
AND y.customer_address_id <= x.customer_address_id
GROUP
BY x.customer_id
, x.customer_address_id
ORDER
BY customer_address_id;

如果性能是个问题,我们可以讨论(或者看看@kickstart 的回答)

关于如果已选择 id,则 MySQL SELECT 递增计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21576397/

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