2016-12-23 54 views
1

我嘗試使用下面的MySQL語句獲取行:分離從選擇查詢的輸出結果按主鍵

+-----------------+ 
| text | b_id | 
+-----------------| 
| a  | 1 |                                            
| b  | 1 |                                        
| c  | 1 |                                            
| e  | 2 | 
| f  | 2 | 

我想在下面的格式來獲取數據:

+---------------+ 
| b_id | Text | 
+-------+-------+ 
| 1 | a,b,c | 
| 2 | e,f | 

我使用像下面的java/mysql api,但它給我的結果是任何b_id一個接一個,如何按照我的要求進行隔離,任何提示都會有用。

Connection conn = new SqlServiceImpl().getConnection("hostName/dbName?", 
     "user", "pwd", ""); 
    String query = 
     "select desc.text,desc.b_id from desc,(select b_id,short_desc from bids where product_id=999) as bi where bi.b_id= desc.bug_id LIMIT 50;"; 
    Statement st = conn.createStatement(); 
    ResultSet rs = st.executeQuery(query); 

while (rs.next()) 
    { 
    int id = rs.getInt("b_id"); 
    String firstName = rs.getString("text"); 
    System.out.format("%s, %s\n", id, firstName); 
    } 

回答

1

簡單。通過b_id列,並在您的SQL語句的結束GROUP_CONCATtext

select 
    b_id, 
    group_concat(text separator ',') text 
from my_table 
group by b_id; 
+0

謝謝你的指針,但我只得到1行,但我已經使用GROUP BY末B_ID ...... – Anand

+1

運行後,「工作SET SESSION group_concat_max_len = 18446744073709551615; 「 – Anand

1

使用GROUP BY b_id,並在你的SELECT部分​​使用GROUP_CONCAT(',', desc.text)集團。

2

簡單的查詢:

SELECT b_id, GROUP_CONCAT(text SEPARATOR ',') as text FROM test1 GROUP BY b_id