I am having data like this
1 A
1 B
1 C
1 D
2 E
2 F
3 G
3 H
3 I
3 J
3 K
by using this query
select ABSTRACTS_ITEM._id,Name
from ABSTRACTS_ITEM , ABSTRACT_AUTHOR , AUTHORS_ABSTRACT
where
ABSTRACTS_ITEM._id = AUTHORS_ABSTRACT.ABSTRACTSITEM_ID
and
ABSTRACT_AUTHOR._id = AUTHORS_ABSTRACT.ABSTRACTAUTHOR_ID
Now, I want to show data like this
1 A,B,C,D
2 EF
and so on..I also know it can achieve by GROUP_CONCAT
function. So, I tried with this
SELECT ABSTRACTS_ITEM._id,
GROUP_CONCAT(ABSTRACT_AUTHOR.NAME) FROM
(select ABSTRACTS_ITEM._id,
Name
from
ABSTRACTS_ITEM , ABSTRACT_AUTHOR , AUTHORS_ABSTRACT
where
ABSTRACTS_ITEM._id = AUTHORS_ABSTRACT.ABSTRACTSITEM_ID
and
ABSTRACT_AUTHOR._id = AUTHORS_ABSTRACT.ABSTRACTAUTHOR_ID)
But, It shows me error. So, what I am doing wrong here. What are the right procedure to achieve that?
You need to add GROUP BY
clause when you are using aggregate function. Also use JOIN
to join tables.
So try this:
SELECT AI._id, GROUP_CONCAT(Name) AS GroupedName
FROM ABSTRACTS_ITEM AI
JOIN AUTHORS_ABSTRACT AAB ON AI.ID = AAB.ABSTRACTSITEM_ID
JOIN ABSTRACT_AUTHOR AAU ON AAU._id = AAB.ABSTRACTAUTHOR_ID
GROUP BY tbl._id;
What you were trying was almost correct. You just needed to add GROUP BY
clause at the end. But the first one is better.
SELECT ID,
GROUP_CONCAT(NAME)
FROM
(select ABSTRACTS_ITEM._id AS ID,
Name
from
ABSTRACTS_ITEM , ABSTRACT_AUTHOR , AUTHORS_ABSTRACT
where
ABSTRACTS_ITEM._id = AUTHORS_ABSTRACT.ABSTRACTSITEM_ID
and
ABSTRACT_AUTHOR._id = AUTHORS_ABSTRACT.ABSTRACTAUTHOR_ID)
GROUP BY ID;
Here my answer to this closed question (it has a good showcase in it). SQL group results by row
You must add an Aggregate Function to your selected field.
The one you want is: GROUP_CONCAT with a custom SEPARATOR ', '
See related MySQL Documentation: https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html
Your Select Query would look like this:
SELECT id_place, placename, GROUP_CONCAT(plant_name SEPARATOR ', ') AS 'plantnames'
FROM BLOOM
JOIN PLACE ON id_place = fk_place
JOIN PLANT ON id_plant = fk_plant
GROUP BY id_place, placename;
Then you get your desired output:
id_place | placename | plantnames |
---|---|---|
1 | New York | orchid, tulip |
2 | London | rosebush, orchid, tulip |
3 | Paris | rosebush, lily, violet |
Here is a DB Fiddle to check this out (MySQL 8.0): https://www.db-fiddle.com/f/sSU7G4kKEaxsLMNweAtLSA/2
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.