2011-11-23 199 views
1

我想從一個表中顯示帖子從另一個表中的某些元值分組,並按其他元值或帖子ID排序,如果選擇「最近」的順序。SQL與GROUP BY和ORDER BY

我想出的最好的是:

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 

但是,這僅如果我們不被任何meta值(m1.value,m2.value或m3.value)分組工作。

+3

你可以張貼一些示例數據和預期的效果?你更有可能得到一個答案,如果你這樣做... –

+0

@Adrian這裏是一個鏈接,我想要得到什麼,我得到:[鏈接](http://img214.imageshack.us/ img214/6563/aseqi.jpg) –

回答

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 
+0

仍然不起作用,因爲我只是從每個組中獲得第一個帖子,而不是最後一個:( –

+0

您正在使用哪個數據庫,以及您面臨的錯誤是什麼? – Teja

+0

i我正在使用MySQL,並且使用你的代碼返回每一行的連接,而不是將它們分組到一起。下面是我得到的[示例](http://img214.imageshack.us/img214/6563/aseqi.jpg)從m1.value分組。 –