Showing posts with label db. Show all posts
Showing posts with label db. Show all posts

Friday, 18 December 2009

A couple of nice MySQL tricks

Do you want to transfer records from one table to another, specifying source and destination columns? Piece of cake:

INSERT INTO destination ( col1 , col2 )
SELECT col3, col4 FROM source


And what if you wish to collapse a subquery in your query results? More complex, but can be easily done with GROUP_CONCAT:

SELECT stuff.., GROUP_CONCAT( column_to_sum_up ) AS newname
FROM main_source
LEFT JOIN other_table_containing_things_to_collapse ON condition
GROUP BY column_in_main_source_that_explains_collapse

Tuesday, 7 October 2008

One query, many records, one result


Sometimes you need to serialize the results of one simple db query. Instead of fetching any single row and appending it to a string, I thought it could be nice (and faster) to delegate the string creation to the database server.

I found out there's no explicit way to do it in MySQL, but I created a nice workaround using the group_concat clause:

SELECT GROUP_CONCAT (field)
FROM table
WHERE index IN (...)
GROUP BY null



Usually, group_concat is used to concatenate the results grouped as specified. Instead, I want to concatenate all the results. Passing null we achieve this result: everything is appended to a single record, and we can fetch a single comma separated string with a single query.

Keep in mind the possibility of issues with the size of the result.