说我有一个像这样的MySQL数据库:
physicians database
Name | Specialty
----------------
Bob Nurse
Susan Nurse
Joan Driver
我想更新数据库,以便将计数少于2的任何专业移到
Other Specialties
所以数据库应该像这样更新:
physicians database
Name | Specialty
----------------
Bob Nurse
Susan Nurse
Joan Other Specialties
该查询的实际数据库要大得多。
我试过这个查询:
UPDATE physicians
(SELECT Specialty FROM physicians GROUP BY Specialty
HAVING COUNT(Specialty) = 1) AS counter
SET Specialty = 'Other Specialties'
WHERE Specity = counter
但是我遇到语法错误,不确定我在做什么错。
最佳答案
试试这个UPDATE
:
UPDATE physicians
SET Specialty = 'Other Specialties'
WHERE Specialty IN (SELECT Specialty
FROM (SELECT Specialty
FROM physicians
GROUP BY Specialty
HAVING COUNT(*) = 1) AS t)
此
UPDATE
使用子查询以使所有Specialty
值唯一。然后,使用这些值执行UPDATE
。注意:子查询被包装在另一个子查询中,因为
SELECT
语句不能直接用于UPDATE
语句来更新同一表。Demo here