SQL选择唯一行

时间:2013-10-11 14:20:34

标签: mysql sql duplicates redundancy

例1:

IDENT | CURRENT | SOURCE
12345 | 12345   | A
23456 | 12345   | B
34567 | 12345   | C

例2:

IDENT | CURRENT | SOURCE
56789 | 56789   | A 

包含3列的表,IDENT,CURRENT和SOURCE。我正在尝试编写一个只在记录中显示*的查询 只有一个唯一的CURRENT记录和IDENT = CURRENT(例2)。有些记录具有相同的CURRENT但IDENT不同(示例1), 这些记录应该从结果中省略。

我正在尝试IDENT = CURRENT的所有当前查询显示类似于示例1的结果。不确定我是否需要以某种方式使用WHERE CURRENT COUNT = 1。

2 个答案:

答案 0 :(得分:0)

select * from table 
where ident=current 
and current in (select current from table group by 1 having count(*)=1)

或没有子查询

select 
min(ident) as ident, 
current, min(source) as source
from table 

where ident=current 
group by current
having count(*)=1

答案 1 :(得分:0)

SELECT M.* 
FROM Table1 AS M 
WHERE M.IDENT = M.CURRENT 
AND (
      SELECT COUNT(*) 
      FROM Table1 AS S 
      WHERE M.IDENT = S.IDENT 
      AND M.CURRENT = S.CURRENT
    ) = 1