sql 查找唯一行排除不同的重复行

sql find uniq row exclude different duplicate row

我有一个 table 有:

id  field_id    todelete
1   x001        0
2   x001        1
3   x001        0
4   x002        1
5   x003        0
6   x003        1
7   x004        0
8   x005        0

由此我需要id 4,它有todelete = 1并且在field_id中是独一无二的。 我目前的解决方案:

array = SELECT field_id WHERE todelete = 1 

从那个数组

SELECT field_id WHERE field_id = array[x] HAVING COUNT(field_id) = 1

似乎是错误的解决方案。我可以只用 SQL 方式吗?谢谢

你走的路很好。当然还有其他解决方案,但只有 2 个可以满足您的需求:

SQL Fiddle

MySQL 5.6 架构设置:

CREATE TABLE Table1
    (`id` int, `field_id` varchar(4), `todelete` int)
;

INSERT INTO Table1
    (`id`, `field_id`, `todelete`)
VALUES
    (1, 'x001', 0),
    (2, 'x001', 1),
    (3, 'x001', 0),
    (4, 'x002', 1),
    (5, 'x003', 0),
    (6, 'x003', 1),
    (7, 'x004', 0),
    (8, 'x005', 0)
;

查询 1:

SELECT id 
FROM Table1
WHERE field_id in 
    (SELECT field_id
     FROM Table1
     WHERE todelete = 1)
GROUP BY field_id
HAVING count(*)=1

Results:

| id |
|----|
|  4 |

查询 2:

SELECT id 
FROM Table1
WHERE todelete = 1
AND field_id in 
    (SELECT field_id
     FROM Table1
     GROUP BY field_id
     HAVING count(*)=1)

Results:

| id |
|----|
|  4 |