【问题标题】:SQL: Select only one row of table with same valueSQL:只选择一行具有相同值的表
【发布时间】:2016-11-11 22:50:12
【问题描述】:

我对 sql 有点陌生,对于我的项目,我需要做一些数据库排序和过滤:

假设我的数据库如下所示:

==========================================
|  id       |       email        | name
==========================================
|   1       |  123@test.com      | John
|   2       |  234@test.com      | Peter
|   3       |  234@test.com      | Steward
|   4       |  123@test.com      | Ethan
|   5       |  542@test.com      | Bob
|   6       |  123@test.com      | Patrick
==========================================

我应该怎么做才能只返回具有相同电子邮件的最后一列:

==========================================
|  id       |       email        | name
==========================================
|   3       |  234@test.com      | Steward
|   5       |  542@test.com      | Bob
|   6       |  123@test.com      | Patrick
==========================================

提前致谢!

【问题讨论】:

  • 正在使用什么 dbms?

标签: sql database filtering


【解决方案1】:

SQL 查询:

    SELECT * FROM test.test1  WHERE id IN (
  SELECT MAX(id) FROM test.test1 GROUP BY email
);

希望这能解决您的问题。谢谢。

【讨论】:

    【解决方案2】:

    在 SQL 中执行此操作的一种通用方法是使用 ANSI 标准 row_number() 函数:

    select t.*
    from (select t.*, row_number() over (partition by email order by id desc) as seqnum
          from t
         ) t
    where seqnum = 1;
    

    【讨论】:

      【解决方案3】:

      这里有一个更清晰的方法:

      SELECT *
      FROM table
      ORDER BY email DESC
      LIMIT 1;
      

      【讨论】:

        【解决方案4】:

        您可以使用以下查询来获取每个 emailMAX id 值:

        SELECT email, MAX(id)
        FROM mytable
        GROUP BY email
        

        使用上面的查询作为派生表可以获得整条记录:

        SELECT t1.*
        FROM mytable AS t1
        JOIN (
          SELECT email, MAX(id) AS id
          FROM mytable
          GROUP BY email 
        ) AS t2 ON t1.id = t2.id
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-21
          • 1970-01-01
          • 2014-07-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-03
          • 2022-01-01
          相关资源
          最近更新 更多