Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL concat with an INNER JOIN

I have 2 tables: manuscript and manuscript_log.

I would like to display for each manuscript the corresponding logs on the same line.

Example: I have two manuscripts 1 and 2. The manuscript 1 has 2 logs and the manuscript 2 has 3 logs.

I would like to get two results in the query, grouped by the manuscrit id:

manuscript_id     manuscript_log
1.                      1,2
2.                     3,4,5

SELECT manuscript.id, manuscript_log.log_number
FROM manuscript INNER JOIN manuscript_log
              ON manuscript.id = manuscript_log.manuscript_id
like image 471
Milos Cuculovic Avatar asked May 27 '13 13:05

Milos Cuculovic


People also ask

Can we use concat in Join SQL?

In SQL, you can also concatenate numerical data from the table in the same way as we concatenate strings. The CONCAT function can also be used to join numeric values.

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.


1 Answers

You can use the GROUP_CONCAT aggregate function

SELECT manuscript.id, GROUP_CONCAT(manuscript_log.log_number)
FROM manuscript INNER JOIN manuscript_log
              ON manuscript.id = manuscript_log.manuscript_id
GROUP BY manuscript.id
like image 150
gbn Avatar answered Sep 26 '22 00:09

gbn