带GROUP BY和ORDER BY的SQL

时间:2011-11-23 15:27:11

标签: mysql sql group-by sql-order-by

我正在尝试显示来自另一个表中某些元值的表格中的帖子,并且如果选择了“最近”订单,则按其他元值或帖子ID排序。

我想出的最好的是:

SELECT `posts`.`id_post`, 
       m1.value AS REGIUNE, 
       m2.value AS JUDET, 
       m3.value AS LOCALITATE, 
       MAX(`posts`.`id_post`) AS ORDERBY 
FROM `posts`
INNER JOIN `posts_meta` m1
    ON(`posts`.`id_post`=m1.`id_post`)
INNER JOIN `posts_meta` m2
    ON(`posts`.`id_post`=m2.`id_post`)
INNER JOIN `posts_meta` m3
    ON(`posts`.`id_post`=m3.`id_post`)
WHERE
    `posts`.`type` = 'published'
AND ( m1.`meta` = 'regiune' )
AND ( m2.`meta` = 'judet' )
AND ( m3.`meta` = 'localitate' )
GROUP BY  posts.id_post
ORDER BY ORDERBY DESC

但是,只有当我们没有按任何元值(m1.value,m2.value或m3.value)进行分组时,这才有效。

1 个答案:

答案 0 :(得分:0)

这个应该有用......

SELECT `posts`.`id_post`, 
       m1.value AS REGIUNE, 
       m2.value AS JUDET, 
       m3.value AS LOCALITATE, 
       MAX(`posts`.`id_post`) AS ORDERBY 
FROM `posts`
INNER JOIN `posts_meta` m1
    ON(`posts`.`id_post`=m1.`id_post`)
INNER JOIN `posts_meta` m2
    ON(`posts`.`id_post`=m2.`id_post`)
INNER JOIN `posts_meta` m3
    ON(`posts`.`id_post`=m3.`id_post`)
WHERE
    `posts`.`type` = 'published'
AND ( m1.`meta` = 'regiune' )
AND ( m2.`meta` = 'judet' )
AND ( m3.`meta` = 'localitate' )
GROUP BY  1,2,3,4
ORDER BY `posts`.`id_post` DESC