您好我遇到了SQL查询问题。如果我想输出表格,以便显示最新评论的产品到最早的评论...请记住,如果输出是产品ID 78,产品ID 79,产品ID 81,产品ID 78,产品ID 81 ,我希望输出为产品ID 78,产品ID 79,产品ID 81.基本上我正在尝试创建一个显示产品最新评论活动的页面。
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 :(得分: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中是相同的。
我们首先按此排序(按最新评论时间戳排序),然后按每个产品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”,您基本上将每个product_id中的COMMENTS表加入 中。您也加入它,使得一个表的time_stamps小于另一个表。 WHERE
条件选择行,使得product_id没有更大的时间戳,即最新评论。