簡體   English   中英

MySQL查詢將多行轉換為一行

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

表格1 在此處輸入圖片說明 表 2 在此處輸入圖片說明 我用來從我的數據庫中獲取第一個表的查詢:

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;

我想以表 2 的形式獲取數據。 我應該寫什么查詢?

這是我在 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;

請參閱聚合函數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

當要合並 1 個以上的值時,可以使用 group_concat() 函數。 但是當你想合並 uniq 值時,你必須使用 distinct 。

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