MySQL使用count更新同一个表中的值

时间:2013-01-03 12:16:16

标签: mysql sql sql-update subquery

我想要做的是为每位患者设置其唯一的患者代码,该代码以1开头,而不是基于行ID。 Id仅指定订单。像这样:

patient_id  patient_code
    2           1
    3           2
    4           3

这是我的疑问:

UPDATE patients p1
SET p1.patient_code = (
    SELECT COUNT( * ) 
    FROM patients p2
    WHERE p2.patient_id <= p1.patient_id 
)

但是它引发了错误:

#1093 - You can't specify target table 'p1' for update in FROM clause

我找到了这个主题:Mysql error 1093 - Can't specify target table for update in FROM clause
但我不知道如何应用已批准的答案来处理COUNT所需的子查询WHERE。

3 个答案:

答案 0 :(得分:7)

UPDATE
    patients AS p
  JOIN
    ( SELECT 
          p1.patient_id
        , COUNT(*) AS cnt 
      FROM 
          patients AS p1
        JOIN 
          patients AS p2
            ON p2.patient_id <= p1.patient_id 
      GROUP BY 
          p1.patient_id
    ) AS g
    ON g.patient_id = p.patient_id
SET 
    p.patient_code = g.cnt ;

答案 1 :(得分:3)

我找到了工作解决方案,但这只是解决方法:

SET @code=0;
UPDATE patients SET patient_code = (SELECT @code:=@code+1 AS code)

答案 2 :(得分:1)

试试这个,

UPDATE patients p1 INNER JOIN
(
    SELECT COUNT(*) as count,patient_id
    FROM patients
    group by patient_id  
)p2 
SET p1.patient_code=p2.count
WHERE p2.patient_id <= p1.patient_id

SQL_LIVE_DEMO