Omar Juvera
Omar Juvera

Reputation: 12297

MySQL: Select multiple records in one line

In a query like this one:

SELECT * 
FROM `Keywords`
WHERE `Page` = 'food'

My results are displayed like so:

| Page   | Keyword |
--------------------
| food   | Pizza   |
--------------------
| food   | Burger  |
--------------------
| food   | Sushi   |
--------------------

How do I write my SQL statement, to get a result like this one?:

| Page | Keyword              |
-------------------------------
| food | Pizza, Burger, Sushi |
-------------------------------

Upvotes: 3

Views: 3332

Answers (2)

Ende Neu
Ende Neu

Reputation: 15783

Use GROUP_CONCAT

SELECT `Page`, GROUP_CONCAT(`Keyword` SEPARATOR ', ') AS 'foods'
FROM `Keywords` 
WHERE `Page` = 'food'
GROUP BY `Page`;

Upvotes: 9

Mark Silverberg
Mark Silverberg

Reputation: 1259

Try this:

SELECT page, group_concat(Keyword separator ', ') as myList
FROM 'Keywords'
WHERE `Page` = 'food'
GROUP BY Keyword;

Also see:

Upvotes: 4

Related Questions