在sqlite中选择唯一记录

时间:2012-09-27 02:04:33

标签: sql sqlite select

考虑一个表

结果(id,key,value)其中key是主键。

示例数据:

id | key      | value
-----------------------
abc| source-1 | 20
abc| source-2 | 30
abc| source-3 | 2 
abc| source-4 | 10
def| source-5 | 1 
ghi| source-6 | 25
jkl| source-5 | 13

我想只返回那些具有给定id的单个条目的记录。所以输出应该是

id | key      | value
------------------------
def| source-5 | 1
ghi| source-6 | 25
jkl| source-5 | 13

请告知。

1 个答案:

答案 0 :(得分:3)

一种方法是使用GROUP BY和HAVING生成一个带有所需id s的派生表,然后加入它:

select results.*
from results
join (
    select id
    from results
    group by id
    having count(*) = 1
) as dt on results.id = dt.id

如果您不喜欢派生表,也可以使用IN:

select *
from results
where id in (
    select id
    from results
    group by id
    having count(*) = 1
)
相关问题