简体   繁体   中英

SQL Concat text from 2 different tables (Multipart messages)

I am trying to make a query in PHP that will give me rows joined together by ID from 2 different tables.

My first table is " outbox " that looks like this.

TextDecoded  |  ID   |  CreatorID
Helllo, m..  |  123  |    Martin
Yes, I wi..  |  124  |    Martin

My second table is " outbox_multipart " that looks very similar.

TextDecoded  |  ID   |  SequencePosition
my name i..  |  123  |         2
s Martin.    |  123  |         3
ll do tha..  |  124  |         2
t tomorrow.  |  124  |         3

In this example there are 2 messages that both consists of 3 parts . The first part is always in outbox table and the rest of them are in outbox_multipart table ordered by SequencePosition .

So the expected result of a query would be this.

       TextDecoded            |  ID   |   CreatorID
Helllo, my name is Martin.    |  123  |    Martin
Yes, I wil do that tomorrow.  |  124  |    Martin

Is this possible somehow?

  • Inner Join between the two tables using ID .
  • Group_Concat() function allows us to concatenate expressions/column values in a Group, with a flexibility of custom sorting, and our choice of delimiter. We can concat outbox_multipart.TextDecoded , based on ascending Order By of outbox_multipart.SequencePosition ; and use empty string '' as delimiter.
  • Use Concat() function to concatenate the fixed starting substring outbox.TextDecoded , to the result string of Group_concat .

Try:

SELECT 
  CONCAT(ob.TextDecoded, 
         GROUP_CONCAT(obm.TextDecoded 
                      ORDER BY obm.SequencePosition ASC 
                      SEPARATOR ''
                     )
        ) AS TextDecoded, 
  ob.ID, 
  ob.creatorID
FROM outbox AS ob 
JOIN outbox_multipart AS obm ON obm.ID = ob.ID 
GROUP BY 
  ob.ID, 
  ob.creatorID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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