2013-04-18 51 views
0

我想在行(未在列),選擇最晚日期如何返回所選行的最大值?

必須「articles_date_added」或「articles_last_modified」表像

Id | ... | ... | articles_date_added | articles_last_modified | ... 

我真正的查詢是這樣的:

select 
    a.articles_id, a.authors_id, a.articles_date_added, 
    a.articles_last_modified, 
    IF(a.articles_last_modified >= a.articles_date_added, 
    a.articles_last_modified, 
    a.articles_date_added) as latestdate, 
    ad.articles_viewed, 
    ad.articles_name, ad.articles_head_desc_tag, 
    COUNT(vh.articles_id) as total_votes, 
    SUM(v.vote_value)/COUNT(v.vote_value) AS vote_avg, 
    au.authors_name, td.topics_name, a2t.topics_id 
from 
    " . TABLE_ARTICLES . " a 
    left join " . TABLE_AUTHORS . " au using(authors_id) 
    left join VOTE_HISTORY vh using (articles_id) 
    left join VOTE v using (vote_id), 
    " . TABLE_ARTICLES_DESCRIPTION . " ad, 
    " . TABLE_ARTICLES_TO_TOPICS . " a2t 
    left join " . TABLE_TOPICS_DESCRIPTION . " td using(topics_id) 
where 
    (a.articles_date_available IS NULL or 
    to_days(a.articles_date_available) <= to_days(now())) and 
    a.articles_status = '1' and a.articles_id = a2t.articles_id and 
    ad.articles_id = a2t.articles_id and 
    ad.language_id = '" . (int)$languages_id . "' 
    and td.language_id = '" . (int)$languages_id . "' 
    and a2t.topics_id = '" . (int)$current_topic_id . "' and 
    au.authors_id = '" . (int)$_GET['filter_id'] . "' 
GROUP BY a.articles_id 
ORDER BY latestdate desc 

正如你可以看到選中我使用

IF(a.articles_last_modified >= a.articles_date_added, 
a.articles_last_modified, a.articles_date_added) as latestdate 

,但它返回1054 - '訂單子句中的未知列'latestdate'

爲什麼?

我在MySql 5.0上。

回答

0

由於添加是一個修改,如果您的a.articles_last_modified在插入行時包含與a.articles_date_added相同的日期,那將是一個好主意。

UPDATE `articles` 
SET `articles_last_modified` = `articles_date_added` 
WHERE `articles_last_modified` = '0000-00-00 00:00:00' 

ALTER TABLE `articles` 
CHANGE COLUMN `articles_last_modified` `articles_last_modified` 
TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; 

這樣你就不需要在clausule

+0

高興向大家報告的概率進行排序這一條件。花了幾個小時)))訣竅是ORDER BY'latestdate'desc的語法。只使用'' – user2296880