Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to Select Everything Except the Max Value

I have this rather complex query that grabs data from three tables, and now I want it to be even more complicated (Oh dear)!

I'd like the last posted feature to be displayed in it's own section of the page, and that's pretty easy by selecting the last entry in the table. However, for the complex query (the main page of the site), I'd like to be able to NOT have this feature displayed.

I'd like to union the following query to my previous query, but it isn't returning the correct results:

SELECT
    features.featureTitle AS title, 
    features.featureSummary AS body, 
    features.postedOn AS dummy, 
    DATE_FORMAT( features.postedOn,  '%M %d, %Y' ) AS posted, 
    NULL, 
    NULL, 
    staff.staffName, 
    features.featureID 
FROM 
    features 
    LEFT JOIN staff ON 
        features.staffID = staff.staffID 
WHERE features.postedOn != MAX(features.postedOn)
ORDER BY dummy DESC LIMIT 0,15

This query returns the following error:

MySQL error: #1111 - Invalid use of group function

Is there any way around this?

like image 302
different Avatar asked Jul 25 '09 19:07

different


1 Answers

The max query needs to be in its own subquery, so your final SQL should be::

SELECT features.featureTitle AS title,
    features.featureSummary AS body, 
    features.postedOn AS dummy,
    DATE_FORMAT( features.postedOn,  '%M %d, %Y' ) AS posted,
    NULL,
    NULL,
    staff.staffName,
    features.featureID 
FROM 
    features 
    LEFT JOIN staff ON 
        features.staffID = staff.staffID
WHERE
   features.postedOn != (select max(features.postedOn) from features)
like image 130
Eric Avatar answered Sep 27 '22 15:09

Eric