0

If I have a table that lists names and ages then can I run a single query that will give me all names of people with a particular age.

e.g.

name      age
----------|-------
alice      20
bob        21
chris      20
dave       23
eric       26
fred       29
greg       20

I want my query to return a list, separated by a comma, of all people who are aged 20.

e.g.

select (concat(name,',')) from people where age='20'

And this outputs:

alice,chris,greg

Obviously I could just do:

select name from people where age='20'

And then loop through the results in PHP but I am trying to do all of this in a query

Chris
  • 4,672
  • 13
  • 52
  • 93

3 Answers3

2
select GROUP_CONCAT(name) AS name from people where age='20'
Deepanshu Goyal
  • 2,738
  • 3
  • 34
  • 61
1

try

select GROUP_CONCAT(name) from people where age='20'
developerCK
  • 4,418
  • 3
  • 16
  • 35
-1

Try this:

SELECT name
FROM people
WHERE age='20'
INTO OUTFILE '/tmp/name.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
Alex
  • 32,506
  • 16
  • 106
  • 171
Dawit
  • 11
  • 3
  • interesting approach - not sure if it work - but incomplete: how to get the file back into PHP? (anyways - I think the accepted answer is much easier) – Alex Sep 13 '13 at 09:24