如何按域分组并删除MySQL数据库中的两个以上结果

时间:2018-10-24 11:12:06

标签: mysql sql select group-by grouping

我有一个问题,
我想对表进行分组,并为每个域仅显示MAX个两个值(例如,按字母顺序排列的硬字符)。

表名称= table1
MySQL数据库

例如: enter image description here

得分:
aa@aa.com
bb@aa.com
aa@example.com
cc@example.com
a@domain.com

如您所见,查询应按域分组,并且每个域仅显示最多两个记录

你能帮我吗?

1 个答案:

答案 0 :(得分:1)

In MySQL 8.0.2 and above, this problem can be solved using Window Functions in a less verbose manner.

For your MySQL version 5.1.73, we can emulate this using Session Variables:

SELECT 
  dt2.Email, 
  dt2.Domain 
FROM 
(
  SELECT 
    @row_num := IF(@dmn <> dt1.Domain, 1, @row_num + 1) AS row_no, 
    @dmn := dt1.Domain AS Domain, 
    dt1.Email 
  FROM 
  (
    SELECT 
      Email, 
      Domain 
    FROM Table1 
    ORDER BY Domain 
  ) AS dt1 
  CROSS JOIN (SELECT @row_num := 0, 
                     @dmn := '') AS user_init_vars 
) AS dt2 
WHERE dt2.row_no <= 2 
ORDER BY dt2.Domain 

DB Fiddle DEMO

You can follow this tutorial to get a basic idea of how this approach works: http://www.mysqltutorial.org/mysql-row_number/