簡體   English   中英

在 group by 和 min mysql 中獲取錯誤數據

[英]get bad data in group by and min mysql

我試圖讓年長的人加入團隊,我使用 group by 和 min 運算符,但它沒有返回正確的值。

這是我的示例數據:

表人:

id   |  name   |  birthdate           |  team_id
-----------------------------------------
1    | person1 |  1993-09-29 15:15:15 | 1
2    | person2 |  1994-09-29 15:15:15 | 1
3    | person3 |  1992-09-29 15:15:15 | 2
4    | person4 |  1990-09-29 15:15:15 | 2

我使用此查詢按團隊獲取老年人:

select id, name, min(birthdate) from persons group by team_id

我希望查詢返回這個數據:

id   |  name   |  min(birthdate)  
----------------------------
1    | person1 |  1993-09-29 15:15:15
4    | person4 |  1990-09-29 15:15:15

但它正在返回:

id   |  name   |  min(birthdate)
----------------------------
1    | person1 |  1993-09-29 15:15:15
3    | person3 |  1990-09-29 15:15:15

正確返回了生日,但名稱和 ID 不正確。

這里發生了什么? 我的錯誤是什么?

這適用於每個 mysql 版本。

但是你沒有指定如果兩個人生日相同會發生什么。

第二個結果顯示了我的查詢會發生什么。

 CREATE TABLE persons ( `id` INTEGER, `name` VARCHAR(7), `birthdate` datetime, `team_id` INTEGER ); INSERT INTO persons (`id`, `name`, `birthdate`, `team_id`) VALUES ('1', 'person1', '1993-09-29 15:15:15', '1'), ('2', 'person2', '1994-09-29 15:15:15', '1'), ('3', 'person3', '1992-09-29 15:15:15', '2'), ('4', 'person4', '1990-09-29 15:15:15', '2');
\n \n\n \n
SELECT p.`id`, p.`name`, p.`birthdate`# FROM persons p INNER JOIN (select team_id, min(birthdate) minbirth from persons group by team_id) mint ON p.birthdate = mint.minbirth AND p.team_id = mint.team_id ORDER By p.team_id,p.`id`
\n身份證 | 姓名 | 生日          \n -: |  :------ |  :------------------\n  1 | 個人1 |  1993-09-29 15:15:15\n  4 | 人4 |  1990-09-29 15:15:15\n
INSERT INTO persons (`id`, `name`, `birthdate`, `team_id`) VALUES ('5', 'person5', '1993-09-29 15:15:15', '1'), ('6', 'person6', '1990-09-29 15:15:15', '2');
\n \n
SELECT p.`id`, p.`name`, p.`birthdate`# FROM persons p INNER JOIN (select team_id, min(birthdate) minbirth from persons group by team_id) mint ON p.birthdate = mint.minbirth AND p.team_id = mint.team_id ORDER By p.team_id,p.`id`
\n身份證 | 姓名 | 生日          \n -: |  :------ |  :------------------\n  1 | 個人1 |  1993-09-29 15:15:15\n  5 | 人5 |  1993-09-29 15:15:15\n  4 | 人4 |  1990-09-29 15:15:15\n  6 | 人6 |  1990-09-29 15:15:15\n

db<> 在這里小提琴

這不是聚合查詢。 這是一個過濾查詢。 我推薦在WHERE子句中使用相關子查詢:

select p.*  -- you can select only the columns you want
from persons p
where p.birthdate = (select min(p2.birthdate)
                     from persons p2
                     where p2.team_id = p.team_id
                    );

另一種非常常見的方法是使用窗口函數:

select p.*
from (select p.*,
             rank() over (partition by team_id order by birthdate) as seqnum
      from persons p
     ) p
where seqnum = 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM