为什么不按团队合作订购?

时间:2013-12-20 17:38:56

标签: mysql drupal

我有新闻表,新闻中有4个类别,我希望得到每个类别的最新消息(按日期排序)。我使用了以下查询:

SELECT node.nid AS nid,
   term_data.tid AS term_data_tid,
   node.type AS node_type,
   node.vid AS node_vid,
   node.title AS node_title,
   node_data_field_blog_overview.field_blog_overview_value AS node_data_field_blog_overview_field_blog_overview_value,
   node_data_field_blog_overview.field_blog_overview_format AS node_data_field_blog_overview_field_blog_overview_format,
   term_data.name AS term_data_name,
   term_data.vid AS term_data_vid,
   users.name AS users_name,
   users.uid AS users_uid,
   node.created AS node_created,
   node_data_field_blog_overview.field_feed_author_name_value AS node_data_field_blog_overview_field_feed_author_name_value,
   node.sticky AS node_sticky
 FROM node node 
 LEFT JOIN term_node term_node ON node.vid = term_node.vid
 LEFT JOIN term_data term_data ON term_node.tid = term_data.tid
 LEFT JOIN content_field_image node_data_field_image ON node.vid = node_data_field_image.vid
 LEFT JOIN content_type_blog node_data_field_blog_overview ON node.vid = node_data_field_blog_overview.vid
 INNER JOIN users users ON node.uid = users.uid
 WHERE (node.type in ('blog')) AND (node.status <> 0)
 GROUP BY term_data_name order by node_created
  LIMIT 5

为什么我没有使用上述查询获取每个类别的最新消息?

1 个答案:

答案 0 :(得分:0)

我认为您的问题始于JOIN类型及其顺序。我建议您在分组数据的任何时候,使用按字段分组的表作为FROM表。

为了简化,首先只获取每个类别最新文章的最新时间:

SELECT term_data.name, MAX(node.node_created) AS mostrecent
FROM term_data
JOIN term_node
  ON term_node.tid = term_data.tid
JOIN node node 
 ON node.vid = term_node.vid
WHERE (node.type in ('blog')) AND (node.status <> 0)
GROUP BY term_data.name

然后你可以用它来获得更多的文章

SELECT {your field list}
FROM [insert above query] AS latest_news
JOIN term_data
  ON term_data.name = latest_news.name
JOIN term_node
  ON term_node.tid = term_data.tid
JOIN node node 
  ON node.vid = term_node.vid
    AND latest_news.mostrecent = node.node_created
JOIN users users
  ON node.uid = users.uid
LEFT JOIN content_field_image node_data_field_image 
  ON node.vid = node_data_field_image.vid
LEFT JOIN content_type_blog node_data_field_blog_overview 
  ON node.vid = node_data_field_blog_overview.vid