Home > Back-end >  How to join two rows in sql using query
How to join two rows in sql using query

Time:11-18

  Table:
 fk_case_id    page_number     page_content
    -----------------------------------------------
         467          1             Hello
         467          2             Good morning
         468          1             No need to add
         469          1             Welcome
         469          2             to home

Python code

mycursor.execute(
        f"select page_number,page_content,fk_case_id from mt_page_file_contents ORDER BY fk_case_id")
myresult = mycursor.fetchall()
prev_case_id = ""
matchstring = ""

for x in myresult:
    page_number = x[0]
    text = x[1]
    print(text)

Solution required:

1) Hello Good morning
2) No need to add
3) Welcome to home

Is there any solution to get "Hello Good morning" by joining two rows based on same fk_case_id

CodePudding user response:

You can Group BY and use GROUP CONCAT

select 
    fk_case_id,GROUP_CONCAT(page_content ORDER BY page_number ASC SEPARATOR ' ') 
    from mt_page_file_contents 
    GROUP BY fk_case_id
ORDER BY fk_case_id
  • Related