我有一个问题,
我想对表进行分组,并为每个域仅显示MAX个两个值(例如,按字母顺序排列的硬字符)。
表名称= table1
MySQL数据库
得分:
aa@aa.com
bb@aa.com
aa@example.com
cc@example.com
a@domain.com
如您所见,查询应按域分组,并且每个域仅显示最多两个记录
你能帮我吗?
答案 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
You can follow this tutorial to get a basic idea of how this approach works: http://www.mysqltutorial.org/mysql-row_number/