代码之家  ›  专栏  ›  技术社区  ›  Svish

MySQL:只输出一些值一次

  •  5
  • Svish  · 技术社区  · 15 年前

    Foo    A
           B
           C
    Bar    B
           D
           E
    

    而不是

    Foo    A
    Foo    B
    Foo    C
    Bar    B
    Bar    D
    Bar    E
    


    更新: WITH ROLLUP 修饰语 GROUP BY . 我也发现它不像我在想的那样,所以我的问题仍然存在。尽管我认为现在没有解决办法。但聪明的人已经证明我错了:P


    更新: 我也应该提到我想要的是一种多对多的关系。在实际的select Foo中,Foo是与会者的名字,我还需要姓氏和其他一些列。A、B、C、D、E是与会者选择的选项。

    attendee (id, first_name, last_name, ...)
    attendees_options (attendee_id, option_id)
    option (id, name, description)
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   Jon Snyder    15 年前

    这会给你

    Foo    A,B,C
    Bar    B,D,E    
    
    SELECT column1, GROUP_CONCAT(column2) FROM table GROUP BY column1
    
        2
  •  0
  •   Joe Stefanelli    15 年前

    在SQL Server中测试过,但我认为它会转换成MySQL。

    create table test (
        id int,
        col1 char(3),
        col2 char(1)
    )
    
    insert into test
        (id, col1, col2)
        select 1, 'Foo', 'A' union all
        select 2, 'Foo', 'B' union all
        select 3, 'Foo', 'C' union all
        select 4, 'Bar', 'D' union all
        select 5, 'Bar', 'E' union all
        select 6, 'Bar', 'F'
    
    select case when t.id = (select top 1 t2.id 
                                 from test t2 
                                 where t2.col1 = t.col1 
                                 order by t2.col1, t2.col2) 
                then t.col1
                else ''
           end as col1, 
           t.col2
        from test t
        order by t.id
    
    drop table test