SELECT state, city
FROM bigcities
which would return
+-------+--------------+
| state | city |
+-------+--------------+
| OH | Cleveland |
| OH | Columbus |
| OH | Cincinnati |
| PA | Pittsburgh |
| PA | Philadelphia |
...
and then process each row and group them by state within your PHP script. Or you could use GROUP_CONCAT as follows:
SELECT state, GROUP_CONCAT(city) AS cities
FROM bigcities
GROUP BY state
which would return:
+-------+--------------------------------+
| state | cities |
+-------+--------------------------------+
| OH | Cleveland,Columbus,Cincinnati |
| PA | Pittsburgh,Philadelphia |
...
The default separator is a comma, but you can define an alternative separator as follows:
SELECT state, GROUP_CONCAT(city SEPARATOR ' -- ') AS cities
FROM bigcities
GROUP BY state
which would return
+-------+--------------------------------------+
| state | cities |
+-------+--------------------------------------+
| OH | Cleveland -- Columbus -- Cincinnati |
| PA | Pittsburgh -- Philadelphia |
...
Greate Help.. Thencs
ReplyDeletesuperb.. but how if i want to group_concat a date field.. it returns BLOB for me....
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteNice post.
ReplyDeleteCheck same here.
http://wamp6.com/php/mysql/concat-multiple-rows-into-a-single-text-string-with-separator-mysql/