我有一张桌子:
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方式吗?感谢
答案 0 :(得分:1)
你走的是好路。当然还有其他解决方案,但这些解决方案可以按照您的意愿运行:
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 |