我有一个类似的数据库:
Name State
Bill CA
Joe NY
Susan CA
我知道我可以得到每个州的记录总数,如下所示:
SELECT State, COUNT(*) as count FROM users GROUP BY State
我正在尝试删除状态总数小于2(或任意数字)的所有记录
像这样(Pseudocode):
DELETE FROM users WHERE totalUsersInState < 2
所以最终的数据库应该是这样的
Name State
Bill CA
Susan CA
这是什么语法?我无法理解。
答案 0 :(得分:1)
我们可以使用连接到内联视图(MySQL术语中的派生表)
首先将其写为SELECT语句
SELECT t.*
FROM users t
JOIN ( SELECT r.state
FROM users r
GROUP
BY r.state
HAVING SUM(1) < 2
) s
ON s.state = t.state
验证这些是我们要删除的行,然后通过替换第一个SELECT关键字将其转换为DELETE语句...
DELETE t.*
FROM ...
请注意,由于连接谓词中的相等比较,这不会删除state
的NULL值的行。
答案 1 :(得分:0)
一个选项,fins所有状态少于2个用户,然后删除这些状态的所有记录。
DELETE FROM
users
WHERE
state IN (SELECT state FROM users GROUP BY state HAVING COUNT(*) < 2)
或(因为< 2
表示“删除他们是州内唯一用户的用户”) ...
DELETE FROM
users
WHERE
NOT EXISTS (SELECT *
FROM users lookup
WHERE lookup.Name <> users.Name
AND lookup.State = users.State
)
-- WHERE NOT EXISTS (any _other_ user that's in the same state)
-- => WHERE this is the only user in the state