如何返回所选行的最大值?

时间:2013-04-18 21:37:38

标签: mysql select row

我正在尝试选择行中的最新日期(不在列中)

表格中必须是'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 - 'order clause

中的未知列'latestdate'

为什么?

我在MySql 5.0上。

1 个答案:

答案 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

中遇到这种情况