在 MySQL 中获取不同的 id

发布于 2024-12-17 12:07:18 字数 525 浏览 1 评论 0原文

我有一个这样的表结构:

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 的行。

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. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白云不回头 2024-12-24 12:07:18

示例查询:

https://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

Example Query:

https://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
葬花如无物 2024-12-24 12:07:18

请将这段代码集成到您的代码中。

表数据:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文