简体   繁体   English

MySQL查询将多行转换为一行

[英]MySQL query to convert multiple rows into one row

Table 1表格1 在此处输入图片说明 Table 2表 2 在此处输入图片说明 Query I am using to get first table from my database:我用来从我的数据库中获取第一个表的查询:

use mydb;
select doc_id,first_name,title,overall_experience_years,address,description_,Price,degree_name from doctor_profile d inner join doctor_education e on d.doc_id=e.doctor_id inner join doc_degree_master m1 on m1.id=e.doc_degree_master_id inner join doctor_specialization s on d.doc_id=s.doctor_id inner join doc_specialization_master m2 on m2.id=s.doc_Specialization_master_id inner join doctor_pricing p on p.doctor_id=d.doc_id;

I want to get data in table 2 form.我想以表 2 的形式获取数据。 What query should I write?我应该写什么查询?

This is my model class in springboot:这是我在 springboot 中的模型类:

@Id
private Long Id;
private String Name;
private String Title;
private int OverallExperience;
private BigDecimal Price;
private String Address;
private List<String> Specialities;
private List<String> Degrees;

See aggregation function GROUP_CONCAT(expr) .请参阅聚合函数GROUP_CONCAT(expr)

select doc_id
     , first_name
     , title
     , overall_experience_years
     , address
     , group_concat(distinct description_) as description_
     , Price
     , group_concat(distinct degree_name) as degree_name
  from doctor_profile d
  join doctor_education e on d.doc_id = e.doctor_id
  join doc_degree_master m1 on m1.id = e.doc_degree_master_id
  join doctor_specialization s on d.doc_id = s.doctor_id
  join doc_specialization_master m2 on m2.id = s.doc_Specialization_master_id
  join doctor_pricing p on p.doctor_id = d.doc_id
 group by doc_id
        , first_name
        , title
        , overall_experience_years
        , address
        , Price

when you want to merge more than 1 values, you can use group_concat() function .当要合并 1 个以上的值时,可以使用 group_concat() 函数。 But when you want to merge uniq values you must use distinct .但是当你想合并 uniq 值时,你必须使用 distinct 。

group_concat(distinct tab_name) and use group by other tab_name except (description_ and degree_name) group_concat(distinct tab_name) 并使用 group by other tab_name 除了 (description_ and degree_name)

select doc_id, first_name, title, overall_experience_years, address
, group_concat(distinct description_) as description_ , Price
, group_concat(distinct degree_name) as degree_name
      from doctor_profile d
      join doctor_education e on d.doc_id = e.doctor_id
      join doc_degree_master m1 on m1.id = e.doc_degree_master_id
      join doctor_specialization s on d.doc_id = s.doctor_id
      join doc_specialization_master m2 on m2.id = s.doc_Specialization_master_id
      join doctor_pricing p on p.doctor_id = d.doc_id
     group by doc_id, first_name, title, overall_experience_years, address, Price

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM