programing

서브 쿼리를 사용한mysql 업데이트 쿼리

goodjava 2022. 11. 2. 00:27

서브 쿼리를 사용한mysql 업데이트 쿼리

아래 문의의 문제점을 알 수 있는 사람이 있습니까?

실행 시 얻을 수 있는 것은 다음과 같습니다.

#1064 - SQL 구문에 오류가 있습니다. MySQL Server 버전에 해당하는 설명서에서 'a where a' 근처에서 사용할 올바른 구문을 확인하십시오.경쟁.ID = 경쟁사.경쟁.8행의 ID'

Update Competition
Set Competition.NumberOfTeams =
(
SELECT count(*) as NumberOfTeams
FROM PicksPoints
where UserCompetitionID is not NULL
group by CompetitionID
) a
where a.CompetitionID =  Competition.CompetitionID

주요 문제는 내부 쿼리가 사용자 이름과 관련될 수 없다는 것입니다.where외부 조항update내부 서브쿼리가 실행되기도 전에 필터가 업데이트되는 테이블에 먼저 적용되기 때문입니다.이러한 상황에 대처하는 일반적인 방법은 멀티 테이블업데이트입니다.

Update
  Competition as C
  inner join (
    select CompetitionId, count(*) as NumberOfTeams
    from PicksPoints as p
    where UserCompetitionID is not NULL
    group by CompetitionID
  ) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = A.NumberOfTeams

데모: http://www.sqlfiddle.com/ #!2/a74f3/1

감사합니다. 저는 이너조인과의 업데이트는 생각지도 못했어요.

원래 쿼리에서는 서브쿼리에 이름을 붙이는 것이 실수였습니다.서브쿼리는 값을 반환해야 하므로 에일리어스를 지정할 수 없습니다.

UPDATE Competition
SET Competition.NumberOfTeams =
(SELECT count(*) -- no column alias
  FROM PicksPoints
  WHERE UserCompetitionID is not NULL
  -- put the join condition INSIDE the subquery :
  AND CompetitionID =  Competition.CompetitionID
  group by CompetitionID
) -- no table alias

경기의 모든 기록에 대해 묘기를 부린다.

주의사항:

이 효과는 mellamokb가 제안한 쿼리와 완전히 동일하지 않습니다. 이 쿼리는 대응하는 PickPoint가 없는 경기 기록을 업데이트하지 않습니다.

부터SELECT id, COUNT(*) GROUP BY idid의 기존 값만 카운트됩니다.

반면 a는SELECT COUNT(*)는 항상 값을 반환합니다.레코드를 선택하지 않으면 0이 됩니다.

이것은 당신에게 문제가 될 수도 있고 아닐 수도 있습니다.

mellamokb 쿼리의 0 인식 버전은 다음과 같습니다.

Update Competition as C
LEFT join (
  select CompetitionId, count(*) as NumberOfTeams
  from PicksPoints as p
  where UserCompetitionID is not NULL
  group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = IFNULL(A.NumberOfTeams, 0)

즉, 대응하는 Pick Point가 발견되지 않으면 Competition을 설정합니다.Number Of Teams to 0.

참을성이 없는 분들을 위해:

UPDATE target AS t
INNER JOIN (
  SELECT s.id, COUNT(*) AS count
  FROM source_grouped AS s
  -- WHERE s.custom_condition IS (true)
  GROUP BY s.id
) AS aggregate ON aggregate.id = t.id
SET t.count = aggregate.count

위와 같이 @mellamokb의 답변은 최대값으로 줄였습니다.

eav_attributes 테이블을 체크하면 다음과 같은 각 이미지 역할의 관련 속성 ID를 찾을 수 있습니다.

그런 다음 이러한 기능을 사용하여 모든 제품에 대해 다른 역할로 설정할 수 있습니다.

UPDATE catalog_product_entity_varchar AS `v` INNER JOIN (SELECT `value`,`entity_id` FROM `catalog_product_entity_varchar` WHERE `attribute_id`=86) AS `j` ON `j`.`entity_id`=`v`.entity_id SET `v`.`value`=j.`value` WHERE `v`.attribute_id = 85 AND `v`.`entity_id`=`j`.`entity_id`

상기의 경우, 모든 「기본」역할은, 같은 제품의 「작은」이미지로 설정됩니다.

언급URL : https://stackoverflow.com/questions/11588710/mysql-update-query-with-sub-query