我有一个看起来像这样的表:
first | last
John | Smith
Bob | dfgdf
John | fggf
John | Smith
我想运行一个查询,该查询将只返回每个名字都有唯一姓氏的行。因此,只应返回Bob dfgdf。目前,我正在分组两次,并检查count = 1,但是有没有更快的方法?
SELECT first FROM (
SELECT first, last FROM table1 GROUP BY first, last
)as t1 GROUP BY first HAVING COUNT(*) = 1
答案 0 :(得分:1)
尝试此版本:
SELECT first
FROM table1
GROUP BY first
HAVING COUNT(*) = COUNT(DISTINCT last);
这仅保留记录记录与不同姓氏计数一致的名字,这意味着每个名字都映射到一个不同的姓氏。
编辑:
如果要从所有匹配的行中选择所有列,则可以尝试:
WITH cte AS (
SELECT first
FROM table1
GROUP BY first
HAVING COUNT(*) = COUNT(DISTINCT last)
)
SELECT t1.*
FROM table1 t1
INNER JOIN cte t2
ON t1.first = t2.first;
答案 1 :(得分:0)
我会这样:
SELECT first
FROM table1
GROUP BY first
HAVING MIN(last) = MAX(last);
实际上,这应该利用table1(first, last)
上的索引。
如果上面没有使用索引,那么我希望最快的方法是:
select distinct on (first) first
from table1 t1
where not exists (select 1 from table1 tt1 where tt1.first = t1.first and tt1.last <> t1.last)
order by first;
这可以利用table1(first, last)
上的索引来提高性能。