httpremix.com

About the Author

Jonah Ellison lives in Seattle, Washington and works at a web firm developing websites and custom web applications for the LAMP solution stack. He enjoys optimization, front-end usability, databases, clean code and clever solutions. Contact him or learn more.

 

Topics

Related Articles

MySQL Tips & Tricks: Using ORDER BY FIELD and GROUP_CONCAT() 2008 Jun 12

Topics: mysql — by jonah ellison

I love databases because I always feel there is a way for retrieving my data in any shape or form I desire. Trying to find the correct syntax can sometimes be frustrating, however. Here are two tricks that have helped me during those special times:

  1. Custom "ORDER BY"
    It's easy to order by ASC or DESC, but what if we want a custom order returned? This is when the FIELD() function comes in handy.

    1. SELECT * FROM table_name ORDER BY FIELD(field_name, 'Small','Medium','Large');

    The disadvantage is that this will slow down your query. For maximum performance, store the field as an ENUM with the values defined in the correct order.

  2. Retrieving values from multiple rows as a single comma-delimited field

    Scenario: We have multiple values spread out across rows a table, but need to retrieve them together in a single field without performing multiple queries. I'm doing this for my archive page--I want to retrieve a list of topic tags for each article, but I want to do it with the same query that selects all my articles. GROUP_CONCAT() is the answer for string concatenation.

    1. SELECT GROUP_CONCAT(wp_terms.slug) AS topic, p.post_date, p.post_title, p.post_count, p.post_name, p.comment_count
    2. FROM wp_posts p
    3. LEFT JOIN wp_term_relationships r ON (r.object_id = p.ID)
    4. LEFT JOIN wp_term_taxonomy t ON (r.term_taxonomy_id = t.term_id)
    5. LEFT JOIN wp_terms ON (wp_terms.term_id = t.term_id)
    6. WHERE t.count> 0 AND t.taxonomy = 'category' AND p.post_status = 'publish'
    7. GROUP BY p.ID
    8. ORDER BY post_date DESC

    The "topic" column could then return values such as "php,mysql,css".


3 Comments »

1. Comment by amit – 2008 August 13 @ 11:50 pm

hi jonah,

i think you love database, i am facing a problem ,if u can help me out.

actually wat i want is:

select a,b,c,d from jonah

now the recordset comes as column a,b,c,d but i want the order to b,a,c,d

and i can not change the sequence in query, so is there any function which reorders the resulting dataset

2. httpremix.com – Comment by jonah ellison – 2008 August 15 @ 1:25 pm

Hi Amit, I think this is what you want:

SELECT b,a,c,d FROM jonah ORDER BY b ASC, a ASC, c ASC, d ASC

3. Comment by Akmal Adnan – 2010 May 3 @ 1:19 am

can you show how to do this For maximum performance, store the field as an ENUM with the values defined in the correct order. . sorry, i am not good with database design.


Leave a comment

RSS feed for comments on this post - TrackBack URL