BenM
BenM

Reputation: 53198

MySQL GROUP BY order

Please consider the following table structure and data:

+--------------------+-------------+
|     venue_name     |  listed_by  |
+--------------------+-------------+
| My Venue Name      |      1      |
| Another Venue      |      2      |
| My Venue Name      |      5      |
+--------------------+-------------+ 

I am currently using MySQL's GROUP BY function to select only unique venue names. However, this only returns the first occurance of My Venue Name, but I would like to return it based on a condition (in this case where the listed_by field has a value > 2.

Essentially here's some pseudo-code of what I'd like to achieve:

Select all records
Group by name
if grouped, return the occurance with the higher value in listed_by

Is there an SQL statement that will allow this functionality?

Edit: I should have mentioned that there are other fields involved in the query, and the listed_by field needs to be used elsewhere in the query, too. Here is the original query that we're using:

SELECT  l1.field_value AS venue_name, 
    base.ID AS listing_id,
        base.user_ID AS user_id,
        IF(base.user_ID > 1, 'b', 'a') AS flag,
        COUNT(img.ID) AS img_num
        FROM ( listingsDBElements l1, listingsDB base )
        LEFT JOIN listingsImages img ON (base.ID = img.listing_id AND base.user_ID = img.user_id and img.active = 'yes')
        WHERE  l1.field_name = 'venue_name'
               AND l1.field_value LIKE '%name%'
               AND base.ID = l1.listing_id
               AND base.user_ID  = l1.user_id
               AND base.ID = l1.listing_id
               AND base.user_ID  = l1.user_id
               AND base.active = 'yes'
    GROUP BY  base.Title  ORDER BY  flag desc,img_num desc

Upvotes: 0

Views: 82

Answers (1)

zerkms
zerkms

Reputation: 254916

As long as you didn't mention other fields - here is the simplest solution:

  SELECT venue_name,
         MAX(listed_by)
    FROM tblname
   WHERE listed_by > 2
GROUP BY venue_name

With other fields it could look like (assuming there is no duplicates in venue_name + listed_by pairs):

    SELECT *
      FROM tblname t1
INNER JOIN (SELECT venue_name,
                   MAX(listed_by) max_listed_by
              FROM tblname
             WHERE listed_by > 2
          GROUP BY venue_name) t2 ON t1.venue_name = t2.venue_name
                                 AND t1.listed_by = t2.max_listed_by

Upvotes: 4

Related Questions