Update with a subquery in MySQL

让人想犯罪 __ 提交于 2019-12-11 18:09:10

问题


I have an update query that I need to run in MySQL and am having some trouble with it. I have spent the last hour researching SO for a solution, but couldn't find one that actually worked. I need to do the following:

UPDATE TABLE1 SET ID = (SELECT TABLE2.ID FROM TABLE2, TABLE1 
WHERE TABLE1.NAME=TABLE2.NAME) WHERE TABLE1.ID IS NULL

I have been getting the Error Code: 1242. Subquery returns more than 1 row error. How can I modify my query to make it run successfully?

Basically, I need to fill in the blanks of all values of one column based on a condition, from another table. Please guide me on this issue. Thank you!


回答1:


UPDATE TABLE1, TABLE2 
  SET TABLE1.ID = TABLE2.ID
  WHERE TABLE1.ID IS NULL
  AND TABLE1.NAME = TABLE2.NAME

should probably do what you want, assuming that NAME is unique accross TABLE1 and TABLE2 for all names.




回答2:


Well, it sounds like your name field is not unique. Your subquery matches more than one row, so you either need to find a unique id to match on other than name, or else, if you want to just take the first result from the subquery do this:

UPDATE TABLE1 SET ID = (SELECT TABLE2.ID FROM TABLE2, TABLE1 WHERE TABLE1.NAME=TABLE2.NAME LIMIT 1) WHERE TABLE1.ID IS NULL




回答3:


SELECT TABLE2.ID FROM TABLE2, TABLE1 WHERE TABLE1.NAME=TABLE2.NAME

this query returning more than one row

Your Query:UPDATE TABLE1 SET ID = ( // here setting one value



TABLE1.NAME=TABLE2.NAME //  more than one matched records are available

Here you are setting id,But when sub query returns more than one row it can not set one value



来源:https://stackoverflow.com/questions/15582172/update-with-a-subquery-in-mysql

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