tags:

views:

204

answers:

2

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?

+2  A: 

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)
Eric
You're a star. Thank you. :-)
different
filtering on the date field is probably not a good idea as it is not guaranteed to be unique - there could be two posts at the same time. filtering by id is better.
Guss
Given my site's frequency of posting featured articles (1 a week or fewer) it'll be a non-issue. Thanks anyway. :-)
different
A: 

the problem you have is that is that you need to find the max (latest) feature from the table, while going over each row, but MAX() is a group function - you have to group all rows to use it.

you can use a sub-select to get the id of the last feature:

WHERE featureId <> (SELECT featureId From features ORDER BY postedOn DESC LIMIT1)

there is a problem with this approach - the subselect is run for every row, but it is not that expensive.

Guss