简体   繁体   English

在MySQL中获取DISTINCT ID

[英]Getting DISTINCT ids in MySQL

I have a table structure like this: 我有一个这样的表结构:

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

I want to get the latest comment from each review sorted by created DESC. 我想从创建的DESC排序的每个评论中获取最新评论。 So I have something like this: 所以我有这样的事情:

SELECT DISTINCT review_id, 'comments' as type FROM comments as MyTable WHERE 
user_id=28 AND deleted=0 ORDER BY created DESC LIMIT 30

So in the above table I want the rows for id = 3 and then id = 2 returned. 因此,在上表中,我希望返回id = 3的行,然后返回id = 2的行。

Example Query: 查询示例:

http://data.stackexchange.com/stackoverflow/s/2143/getting-distinct-ids-in-mysql 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

Please integrate this code in your code. 请将此代码集成到您的代码中。

Table data: 表格数据:

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

Run query: 运行查询:

SELECT DISTINCT id, review_id, 'comments' AS TYPE 
FROM mytable
WHERE user_id = 28
AND deleted = 0
AND id = (
  SELECT max( id )
  FROM mytable 
)

Result: 结果:

id  review_id    TYPE
3   10       comments

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM