如果值存在于另一条记录中,MySQL 选择记录

发布于 2024-11-30 00:51:05 字数 532 浏览 0 评论 0原文

我需要从表中选择记录,但前提是存在比当前记录上的值大 1 的值并且用户相同。

这是我当前的表:

    +---------+------------+-----------+
    | user_id | scheme_val | scheme_id |
    +---------+------------+-----------+
    |    1    |   text1    |     1     |
    |    1    |   text2    |     2     |
    |    2    |   text1    |     1     |
    +---------+------------+-----------+

所以基本上我需要选择所有记录,只要没有来自同一用户的具有更高 schema_id 的其他记录。因此,在此表上,它只会返回第二行和第三行,而不返回第一行。原因是对于用户 1 的第一行,表中还有另一行的 schema_id 比该行大。

我希望这是有道理的?

提前致谢。

I need to select records from a table, but only if a value exists 1 greater than a value on the current record and the user is the same.

This is my current table:

    +---------+------------+-----------+
    | user_id | scheme_val | scheme_id |
    +---------+------------+-----------+
    |    1    |   text1    |     1     |
    |    1    |   text2    |     2     |
    |    2    |   text1    |     1     |
    +---------+------------+-----------+

So basically I need to select all records, so long as there isn't another record from the same user with a higher scheme_id. So on this table it would only bring back the second and third row and not the first row. The reason being for the first row for user 1, there is another row in the table with a scheme_id 1 greater than that row.

I hope this makes sense?

Thanks in advance.

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

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

发布评论

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

评论(2

且行且努力 2024-12-07 00:51:05

尝试以下查询。它肯定会起作用,但不会是最优化的。它有点开箱即用,但我很想知道是否有人有其他解决方案。

SELECT
    *
FROM
    users
WHERE
    CONCAT(user_id, ":", scheme_id)
        IN
            (
                SELECT
                    CONCAT(user_id, ":", MAX(scheme_id))
                FROM
                    users
                GROUP BY
                    user_id
            )

Try the following query. It will work for sure, but won't be the most optimized one. Its a little out of the box, but i'm very much interested to hear if any one has any other solutions.

SELECT
    *
FROM
    users
WHERE
    CONCAT(user_id, ":", scheme_id)
        IN
            (
                SELECT
                    CONCAT(user_id, ":", MAX(scheme_id))
                FROM
                    users
                GROUP BY
                    user_id
            )
话少情深 2024-12-07 00:51:05

应该可以使用子查询连接同一个表:

select * from user u1 where u1.scheme_id =
( select max(u2.scheme_id) from user u2
  where u1.user_id = u2.user_id );

Should be possible with a subquery joining with the same table:

select * from user u1 where u1.scheme_id =
( select max(u2.scheme_id) from user u2
  where u1.user_id = u2.user_id );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文