MySQL Update Subset Having

吃可爱长大的小学妹 提交于 2019-12-06 21:38:13

问题


I have three tables: contacts, domains, and contacts_domains, which form a many-to-many relationship.

I would like to run a query that updates the contacts_domains table, but only for domains that have exactly one contact.

I know how to SELECT the rows I'm interested in, but not how to UPDATE them.

SELECT domain_id, contact_id, dominant
FROM contacts_domains
GROUP BY domain_id
HAVING COUNT(contact_id) = 1

I want to set contacts_domains.dominant = 1 for all these results.

Thanks!


回答1:


The simplest solution:

UPDATE contacts_domains cd SET cd.dominant = 1
WHERE cd.id IN (
SELECT dominant_id
FROM contacts_domains
GROUP BY domain_id
HAVING COUNT(contact_id) = 1
)

Edited.




回答2:


I had problem like this. Try with joining with table make with select:

UPDATE contacts_domains cd, 
 (SELECT id FROM contacts_domains GROUP BY domain_id
   HAVING COUNT(contact_id) = 1) AS cdtmp
SET cd.dominant = 1
WHERE cd.id = cdtmp.id

Hope it will help



来源:https://stackoverflow.com/questions/8127257/mysql-update-subset-having

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!