2012-03-13 115 views
0

您好我有一個SQL查詢的問題。如果我想輸出表格,以便它顯示最新評論中的產品以及最早發表的評論......請記住,如果輸出是產品ID 78,產品ID 79,產品ID 81,產品ID 78,產品ID 81 ,我想輸出爲產品ID 78,產品ID 79,產品ID 81.基本上我試圖創建一個頁面顯示產品上的最新評論活動。SQL查詢按訂單複雜排序

SELECT comments.products_products_id, products.name, products.minilocation, products.users_user_id, 
comments.comment, comment_id, comments.time_stamp, users.username, users.miniavatar FROM products 
INNER JOIN comments ON comments.products_products_id = products.products_id INNER JOIN users ON users.user_id = comments.products_users_user_id 
ORDER BY comments.time_stamp DESC 
+0

Is comments.products_products_id actually comments.products_id? – 2012-03-13 00:58:06

+0

所以你想要通過最新的評論來訂購,確保一件物品的所有評論都粘在一起? – 2012-03-13 00:59:09

+0

你所有的ID都是正確的。基本上只是想把最新評論活動的產品放在最前面。不要任何重複的產品ID – Anonymous 2012-03-13 01:02:26

回答

2

取決於如果你只是想每PRODUCT_ID最近的評論,或者如果你想所有的意見,而只是由PRODUCT_ID分類,其中有最新評論該產品是第一個。


如果你想所有意見,由PRODUCT_ID,其中product_ids在最新評論的排序分組(即看到最新的時間戳順序如何提示產品是爲了(3,1,2 ):

product_id comment_timestamp 
    3    2012-03-13 
    3    2012-03-09 
    3    2012-03-01 
    1    2012-03-12 
    1    2012-01-01 
    2    2012-03-11 

然後這裏是你如何能做到這一點 - 通過它才能找出每個產品的最新時間戳,加入該到你的主查詢和:

SELECT comments.products_products_id, products.name, 
     products.minilocation, products.users_user_id, 
     comments.comment, comment_id, comments.time_stamp, 
     users.username, users.miniavatar 
FROM products 
-- NEW JOIN: 
INNER JOIN (SELECT product_id, MAX(time_stamp) as latest 
      FROM comments 
      GROUP BY product_id) latest 
     ON latest.product_id = products.product_id 
-- as before. 
INNER JOIN comments ON comments.products_products_id = products.products_id 
INNER JOIN users ON users.user_id = comments.products_users_user_id 
-- NEW SORT: 
ORDER BY latest.latest DESC, comments.time_stamp DESC 

加入的新表格是最大值(即最新的)每個產品ID的時間戳。 這將在單個產品ID中相同。

我們是用這種第一(通過最新的評論時間戳排序),並然後內的每個產品編號排序個人評論時間戳


如果你想每PRODUCT_ID最近的評論,即

product_id comment_timestamp 
    3    2012-03-13 
    1    2012-03-12 
    2    2012-03-11 

然後使用:

SELECT comments.products_products_id, products.name, 
     products.minilocation, products.users_user_id, 
     comments.comment, comment_id, comments.time_stamp, 
     users.username, users.miniavatar 
FROM comments 
-- NEW SELF-JOIN 
LEFT JOIN comments c2 ON comments.products_products_id = c2.products_products_id 
        AND comments.time_stamp < c2.time_stamp 
INNER JOIN products ON comments.products_products_id = products.products_id 
INNER JOIN users ON users.user_id = comments.products_users_user_id 
-- new condition 
WHERE c2.time_stamp IS NULL 
ORDER BY comments.time_stamp DESC 

這種類型的查詢被稱爲 「每組最大的N」,和你基本上每個產品ID都加入您的COMMENTS表格以內。你也加入它,使得一個表的time_stamps小於另一個。 WHERE條件選擇行,使得product_id沒有更大的時間戳,即最新的評論。

+0

我認爲它的工作。除了comment_id之外,我改爲comments.comment_id。我最複雜的查詢呢。謝謝。 – Anonymous 2012-03-13 01:27:53