我的表:
NAME SURNAME
John Smith
Jane Smith
Alice Smith
James Bond
James Cameroon
David Beckham
我有一个数据库,我希望每个k
选择SURNAME
行。对于k=1
它:
SELECT * FROM people GROUP BY SURNAME;
,输出为:
Alice Smith
James Bond
James Cameroon
David Beckham
我找不到查询k=2
的方法,我会得到(如果有的话)2个史密斯,2个债券,2个喀麦隆等或一般:k史密斯,k债券,k喀麦隆等等。如果有SURNAME
人少于k人,则选择所有人。可以在MySQL
吗?
答案 0 :(得分:1)
您可以使用以下查询:
SELECT NAME, SURNAME
FROM (
SELECT NAME, SURNAME,
@rn := IF(@s = SURNAME, @rn + 1,
IF(@s := SURNAME, 1, 1)) AS rn
FROM mytable
CROSS JOIN (SELECT @rn := 0, @s = '') AS vars
ORDER BY SURNAME) AS t
WHERE t.rn <= 3
以上查询显示了k=3
的示例。它将从OP中引用的样本表中选择所有记录。
答案 1 :(得分:0)
SELECT Name,Surname,Count(SurName) AS k FROM people
GROUP BY SURNAME
HAVING k>=2
答案 2 :(得分:-1)
您可以区分surname
并使用相同的表格加入,但仅限于k
。通过这种方式,您将获得每个surname
k
行
SELECT DISTINCT(`surname`)
LEFT JOIN (
SELECT `name` FROM `people` p2 where p2.surname = p1.surname limit 2
) x
FROM `people` p1