使用mysql子查询更新错误:子查询返回多于1行

时间:2018-04-11 14:59:53

标签: mysql subquery

我正在尝试使用historical_state_order表的最新字段更新订单表的字段'cancellation_date',但是它给出了一个错误“Subquery返回超过1行”而我无法做到,有人可能开导我?谢谢。

更新查询:

    UPDATE orden o 
SET 
    fecha_cancelacion = (SELECT             
                MAX(CAST(fecha AS DATETIME))
        FROM
            historico_estados_orden h
        WHERE
            o.id_orden = h.id_orden
                AND h.estado_origen = 'OrdenWorkflow/cancelada'
                AND h.estado_fin = ''
                OR h.estado_fin = 'OrdenWorkflow/cancelada'
                AND h.deleted = 0
                AND id_orden NOT IN (3258 , 3221, 3219, 2857, 2836, 2861, 2884, 2878, 3442, 2876)
        GROUP BY h.id_orden)
WHERE
    o.status = 'OrdenWorkflow/cancelada'
        AND o.deleted = 0
        AND o.id_orden NOT IN (3258 , 3221, 3219, 2857, 2836, 2861, 2884, 2878, 3442, 2876);

2 个答案:

答案 0 :(得分:1)

您不需要在子查询中使用UPDATE orden o SET fecha_cancelacion = ( SELECT MAX(CAST(fecha AS DATETIME)) FROM historico_estados_orden h WHERE o.id_orden = h.id_orden AND h.estado_origen = 'OrdenWorkflow/cancelada' AND h.estado_fin IN ('', 'OrdenWorkflow/cancelada') AND h.deleted = 0 ) WHERE o.status = 'OrdenWorkflow/cancelada' AND o.deleted = 0 AND o.id_orden NOT IN (3258, 3221, 3219, 2857, 2836, 2861, 2884, 2878, 3442, 2876); ,因为您只需要返回一个最大值:

id_orden

另请注意,对id_orden的限制不需要再次出现在子查询中,因为它已存在于外部查询中。外部查询和子查询之间存在constants匹配的条件。

答案 1 :(得分:0)

LIMIT 1

UPDATE orden o 
SET 
    fecha_cancelacion = (SELECT             
                MAX(CAST(fecha AS DATETIME))
        FROM
            historico_estados_orden h
        WHERE
            o.id_orden = h.id_orden
                AND h.estado_origen = 'OrdenWorkflow/cancelada'
                AND h.estado_fin = ''
                OR h.estado_fin = 'OrdenWorkflow/cancelada'
                AND h.deleted = 0
                AND id_orden NOT IN (3258 , 3221, 3219, 2857, 2836, 2861, 2884, 2878, 3442, 2876)
        GROUP BY h.id_orden LIMIT 1)
WHERE
    o.status = 'OrdenWorkflow/cancelada'
        AND o.deleted = 0
        AND o.id_orden NOT IN (3258 , 3221, 3219, 2857, 2836, 2861, 2884, 2878, 3442, 2876);

如果您需要 ORDER BY fecha 也这样做