获取数据库中单行的多个行数据

huangapple go评论65阅读模式
英文:

MySQL Get multple rows for a single row in db

问题

你可以在MySQL中使用以下查询来实现这个目标:

SELECT id, (@row_number:=CASE WHEN @id=id THEN @row_number+1 ELSE 1 END) AS seq
FROM (SELECT id FROM tags ORDER BY id) AS t
JOIN (SELECT @row_number:=0, @id:=NULL) AS r;

这个查询会为每个标签ID生成一个序列号(seq),并按照ID进行排序。

英文:

I have a select query

select id from tags

Which returns data like

id
--
1
2

I want to get data with a sequence number as shown below

id seq
-- ---
1  1
1  2
1  3
1  4
1  5
2  1
2  2
2  3
2  4
2  5

How can I achieve this in mysql

答案1

得分: 2

以下是您要翻译的内容:

select id, seq
from tags
cross join (
    select 1 seq union all select 2 union all select 3 union all select 4 union all select 5
) seqs
order by id, seq

或者

with recursive seqs as (
    select 1 seq
    union all
    select seq+1
    from seqs
    where seq < 5
)
select id, seq
from tags
cross join seqs  
order by id, seq
英文:
select id, seq
from tags
cross join (
    select 1 seq union all select 2 union all select 3 union all select 4 union all select 5
) seqs
order by id, seq

Or

with recursive seqs as (
    select 1 seq
    union all
    select seq+1
    from seqs
    where seq &lt; 5
)
select id, seq
from tags
cross join seqs  
order by id, seq  

答案2

得分: 0

你可以按照这里指定的方式使用递增变量;

在你的情况下,查询应该像这样:

SET @rowcount=0;
SELECT id, @rowcount:=@rowcount+1 as seq from tags;

英文:

You can use an incremental variable as specified here;

In your case, the query should be like this:

SET @rowcount=0;
SELECT id, @rowcount:=@rowcount+1 as seq from tags;

huangapple
  • 本文由 发表于 2023年5月11日 12:41:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定