在mysql中多次重复结果

时间:2014-04-21 11:46:13

标签: mysql sql

我有一个id没有字段的表,我真正想要的是结果raw将重复没有提交时间,如果no字段是2那么raw必须在结果中重复两次。 这是我的示例表结构:

     id  no   
     1   3
     2   2
     3   1

现在我需要得到一个结果:

1  3
1  3 
1  3
2  2
2  2
3  1

我尝试编写mysql查询以获得上面的结果,但失败了。

4 个答案:

答案 0 :(得分:4)

您需要一个数字表来完成此任务。只需三个值,这很容易:

select t.id, t.no
from t join
     (select 1 as n union all select 2 union all select 3
     ) n
     on t.no <= n.no;

答案 1 :(得分:0)

此查询必须执行您想要实现的目标:

select t.id, t.no from  test t cross join  test y where t.id>=y.id

答案 2 :(得分:0)

没有完全解决你的问题,但这个可以帮助

set @i=0;

select 
    test_table.*
from 
     test_table
join 
    (select
         @i:=@i+1 as i
     from 
         any_table_with_number_of_rows_greater_than_max_no_of_test_table
     where 
         @i < (select max(no) from test_table)) tmp on no >= i
order by
     id desc

答案 3 :(得分:0)

编辑: 这是在SQL Server上。我在线检查了一下,发现CTE也可以在MySQL上工作。只是无法让他们在SQLFiddle上工作

尝试一下,删除不需要的列

create table #temp (id int, no int)

insert into #temp values (1, 2),(2, 3),(3, 5)

select * from #temp

;with cte as
    (
        select id, no, no-1 nom from #temp
        union all
        select c.id, c.no, c.nom-1 from cte c inner join #temp t on t.id = c.id and c.nom < t.no and c.nom > 0
    )

select * from cte order by 1

drop table #temp
相关问题