我有一个像这样的表结构:
Comments table
id review_id user_id created comments deleted
1 10 28 2011-10-12 "hi" 0
2 11 28 2011-10-13 "yo" 0
3 10 28 2011-10-15 "bye" 0
我想从每个评论中获取按创建的DESC排序的最新评论。所以我有这样的事情:
SELECT DISTINCT review_id, 'comments' as type FROM comments as MyTable WHERE
user_id=28 AND deleted=0 ORDER BY created DESC LIMIT 30
所以在上面的表中我想要id = 3的行,然后返回id = 2。
答案 0 :(得分:3)
示例查询:
http://data.stackexchange.com/stackoverflow/s/2143/getting-distinct-ids-in-mysql
SELECT id,comment
FROM comments
WHERE id IN (
SELECT MAX(id)
FROM comments
WHERE user_id=28 AND deleted=0
GROUP BY review_id )
ORDER BY created DESC
答案 1 :(得分:1)
请将此代码集成到您的代码中。
表格数据:
id review_id user_id created comments deleted
1 10 28 2011-10-12 "hi" 0
2 11 28 2011-10-13 "yo" 0
3 10 28 2011-10-15 "bye" 0
运行查询:
SELECT DISTINCT id, review_id, 'comments' AS TYPE
FROM mytable
WHERE user_id = 28
AND deleted = 0
AND id = (
SELECT max( id )
FROM mytable
)
结果:
id review_id TYPE
3 10 comments