2010-11-01 58 views
5

我想我以前做過這個,但它也可能是PHP的一個函數。我想是做一個MySQL查詢(在MySQL客戶端,而不是PHP),並得到例如MySQL:只輸出一次值

Foo A 
     B 
     C 
Bar B 
     D 
     E 

而不是

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

這當然只讓SENCE,如果它被責令通過第一列。不知道是否是可能的,但就像我說的,我的意思是要記得曾經做過這個,不過怎麼也想不起或者如果它是通過一些PHP「神奇」 ......


更新:突然想起我在哪裏用過它。我在想的是WITH ROLLUP修改器GROUP BY但是我也發現它不會做我在這裏想的,所以我的問題依然存在。雖然我現在不認爲有解決方案。但是,聰明的人都證明我錯了之前:P


更新:也許應該還提到,我想這什麼是許多一對多的關係。在實際中,選擇Foo將成爲與會者的第一個名字,我還想要姓氏和其他一些列。 A,B,C,D,E是與會者選擇的選項。

attendee (id, first_name, last_name, ...) 
attendees_options (attendee_id, option_id) 
option (id, name, description) 
+0

什麼是可以接受的 - NULL,零長度字符串? – 2010-11-01 21:33:25

+0

兩者都可能工作。 – Svish 2010-11-01 23:31:29

回答

1

這會給你

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

SELECT column1, GROUP_CONCAT(column2) FROM table GROUP BY column1 
+0

酷,不知道'group_concat'語句。甚至支持多列,排序和自定義分隔符...可能最終使用此... – Svish 2010-11-01 23:53:26

0

在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 
+0

需要一些調整,但實際上爲這個例子工作。猜猜這將需要那些可能重複的列中的每個列的大'case'塊中的一個...? – Svish 2010-11-01 23:52:30