简体   繁体   English

SQL选择唯一实体

[英]SQL Select Unique Entires

I have in my table: 我在桌上:

ID Name   Age
1  James  15
2  James  16
3  Joseph 16
4  Joseph 18
5  Steve  4

and I want to return: 我想返回:

5 Steve 4
1 James 15
3 Joseph 16

ie. 即。 Unique entries based on the Name row (choose the one with lowest ID when there are multiple of the same Name), and ordered by Age 根据“名称”行的唯一条目(当存在多个相同名称时,选择ID最低的条目),并按年龄排序

What would be the correct SQL statement? 什么是正确的SQL语句?

I have: 我有:

Select * FROM table Where True GROUP BY Name ORDER BY Age

It seems to be returning a lot of unique results, but it's too slow (table has >250,000 entries and it takes >30seconds to process), I wonder if there is a faster way to do this? 它似乎返回了很多独特的结果,但是它太慢了(表有> 250,000个条目,并且要花费> 30秒的时间来处理),我想知道是否有更快的方法来做到这一点?

try this 尝试这个

SELECT * 选择 *
FROM table WHERE ID in (SELECT MIN(ID) FROM table group by name) FROM table WHERE ID(按名称选择SELECT MIN(ID)FROM table组)
ORDER by age 按年龄排序

You just group the datasets by name and get MIN(ID) and use this as 'where' condition for your selection 您只需按名称对数据集进行分组并获得MIN(ID)并将其用作选择的“ where”条件

Another way of querying this, usually better where performance is needed, provided you have (and that's NOT an option here) an INDEX on Name : 查询此内容的另一种方法,通常是在需要性能的地方,如果您在Name上具有INDEX(并且在这里不是选择),则通常会更好:

SELECT *
FROM your_table t1
LEFT JOIN your_table t2 ON t1.Name = t2.Name AND t2.ID < t1.ID
WHERE t2.ID IS NULL;

A quick explanation here . 这里有一个简短的解释

Since you want to select based on the minimum ID , which is a unique field, you just need to get the minimum ID s per name first, then join those ID s to the main table. 由于要基于最小ID进行选择,这是一个唯一字段,因此您只需要首先获取每个名称的最小ID ,然后将这些ID连接到主表即可。 This will be much faster than using a subquery in a WHERE as the subselect of the minimums gets executed just one time, whereas a subquery would execute for each row in the main table (250,000+ times!). 这将比在WHERE使用子查询快得多,因为最小值的子选择仅执行一次,而子查询将对主表中的每一行执行(250,000次以上!)。

SELECT
    b.*
FROM
    (
        SELECT MIN(ID) AS minID
        FROM tbl
        GROUP BY Name
    ) a
INNER JOIN
    tbl b ON a.minID = b.ID
ORDER BY
    b.Age

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM