根据主键从选择查询中分离输出结果

时间:2016-12-23 13:36:07

标签: java mysql

我正在尝试使用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);
  }

3 个答案:

答案 0 :(得分:2)

简单查询:

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

答案 1 :(得分:1)

简单。按b_id列分组,GROUP_CONCAT text列分组

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

答案 2 :(得分:1)

在SQL语句末尾使用GROUP BY b_id,并在SELECT部分​​使用GROUP_CONCAT(',', desc.text)