假设我有一个像这样的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
但是我收到语法错误,不确定我做错了什么。
答案 0 :(得分:2)
试试这个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
语句来更新同一个表。
答案 1 :(得分:2)
如果您想使用查询结构,可以将其更改为
UPDATE physicians inner join
(SELECT Specialty FROM physicians GROUP BY Specialty
HAVING COUNT(Specialty) = 1) AS counter on physicians.speciality = counter.specialty
SET Specialty = 'Other Specialties'
答案 2 :(得分:1)
update physicians
set Specialty = 'Other Specialties'
where Specialty in (
select Specialty
from physicians
group by Specialty
having COUNT(Specialty) < 2
)
更新: 更新医生 SET Specialty ='其他特产' 特色IN(SELECT专业 FROM(选择专业 来自医生 GROUP BY专业 有计数(专业)&lt; 2)AS空间性值);