Subquery returns more than 1 row - MySQL

。_饼干妹妹 提交于 2021-02-10 15:03:23

问题


UPDATE `pams_faker_lead_location` 
SET `location` = ( SELECT location FROM pams_leads WHERE pams_leads.location_id = pams_faker_lead_location.id   )

I dont know when i run the query in Mysql , this error occur.

#1242 - Subquery returns more than 1 row

anyone can help me solve the problem ?


回答1:


This query:

SELECT location FROM pams_leads WHERE pams_leads.location_id = pams_faker_lead_location.id

gives you more than 1 row. You must change something because if you need update value you need exactly one row




回答2:


Try this:

UPDATE A
SET A.`location` =  B.`location`
FROM `pams_faker_lead_location` A
JOIN `pams_leads` B ON B.location_id = A.id



回答3:


Use joins instead

update pams_faker_lead_location l
inner join pams_leads pm on pm.location_id = l.id
set l.location = pm.location



回答4:


What part of the error message do you not get? The subquery is returning more than one row, so you need to decide which value you want. Here are two common methods for getting one row:

One uses an aggregation function, such as MAX() or MIN():

UPDATE pams_faker_lead_location fll 
    SET location = (SELECT MAX(l.location)
                    FROM pams_leads l
                    WHERE l.location_id = fll.id
                    LIMIT 1
                   );

The other uses LIMIT. This would normally have an ORDER BY as well, so you can choose the value you want:

UPDATE pams_faker_lead_location fll 
    SET location = (SELECT l.location
                    FROM pams_leads l
                    WHERE l.location_id = fll.id
                    LIMIT 1
                   );

The error is occurring because the data is not what you expect it to be. Using a method such as JOIN merely hides the problem -- and might incur significant performance penalties if there are lots and lots of duplicates.



来源:https://stackoverflow.com/questions/49750348/subquery-returns-more-than-1-row-mysql

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