按博客发布日期排序的sql返回类别

时间:2014-04-24 11:59:56

标签: sql blogs categories subquery

我在Wordpress网站上发表文章。帖子可以包含更多类别(表格wp_terms)。现在我想要一个查询,返回所有术语名称的列表,按博客文章日期排序。我在SELECT查询中尝试过SELECT,但这不起作用......我怎么能这样做并返回按文章日期排序的类别?

wp_posts (例如):

|ID------|post_title------------------|post_date-|
|1       |Test title                  |2014-05-05|
|2       |Test title 2                |2014-04-01|
|3       |Last test title             |2014-02-02|
|4       |Another blog item           |2014-01-06|

wp_terms

|term_id|name---------|
|1      |computers    |
|2      |home         |
|3      |work         |

wp_term_relationships

|object_id|term_taxonomy_id|term_order|
|1        |2               | 0        |
|1        |1               | 0        |
|2        |3               | 0        |

wp_term_taxonomy

|term_taxonomy_id | term_id |
|1                |1        |
|2                |2        |
|3                |3        |
|4                |4        |

这是我当前的查询,但这不起作用......

SELECT t.*, p.*  FROM wp_terms AS t 
JOIN wp_term_taxonomy AS tt ON tt.term_id = t.term_id
JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tr.term_taxonomy_id 
LEFT JOIN ( SELECT `ID`, `post_title`, max(`post_date`) as `date` FROM wp_posts
GROUP BY `ID` ) as p on p.`ID`= tr.`object_id` GROUP BY t.`term_id` ORDER BY p.`date` desc

1 个答案:

答案 0 :(得分:0)

仍然不确定你想要实现的目标。但这是你的查询运行没有错误

SELECT t.*, p.* 
FROM wp_terms AS t JOIN wp_terms_taxonomy AS tt 
    ON tt.term_id = t.term_id 
JOIN wp_terms_relationship AS tr 
    ON tr.term_taxonomy_id 
        = tr.term_taxonomy_id LEFT JOIN 
( SELECT ID, post_title, max(post_date) as date 
 FROM wp_posts 
 GROUP BY ID , post_title) as p on p.ID= tr.object_id 
GROUP BY t.term_id,t.name,p.id,p.post_title,p.date
ORDER BY p.date desc

fiddle