Next Tutorial

Drupal 7 Tutorial Part 16: Drupal 7 Reports & Logs Explained

How to query mysql using distinct and order by on more than one field

Submitted by anilsagar on Fri, 01/01/2010 - 01:50

I came through a very strange problem. That is using DISTINCT on multiple columns at the same time using ORDER BY condition. When i don't use DISTINCT it returns correct order but on DISTINCT condition ORDER BY effect is lost. My query is some thing like this.

SELECT c.title, a.nid, b.filepath FROM content_type_x as a
LEFT JOIN files as b ON a.field_show_image_fid = b.fid
ORDER BY a.nid

If i use DISTINCT for the above query then the sorting order is lost. The solution i found is using temp table to store the results temporarily and then use DISTINCT command. It works like a charm. The modified query is something like this

SELECT DISTINCT * FROM ((
SELECT c.title, a.nid, b.filepath FROM content_type_x as a
LEFT JOIN files as b ON a.field_show_image_fid = b.fid
ORDER BY a.nid) as tempx )

©2010 AnilSagar. All rights reserved. Drupal theme by Kiwi Themes.