2

我有这个联盟声明:

(SELECT id FROM bby_venta_co WHERE nom_agrupacion = 'CAFE NESCAFE' 
AND promocion_id = 100000189 
AND ticket_id = 156 
AND fondo_fijo_id = 14 
AND caja_id = 1 ORDER BY costo DESC LIMIT 1)
UNION ALL
(SELECT id FROM bby_venta_co WHERE nom_agrupacion = 'CAFE INTERNA' 
AND promocion_id = 100000189 
AND ticket_id = 156 
AND fondo_fijo_id = 14 
AND caja_id = 1 ORDER BY costo DESC LIMIT 1);

这给我带来了两行(214,158),我需要这些信息来执行我的更新

UPDATE bby_venta_co SET tupla_usada = 1 WHERE id in(214,158); 

但是当我尝试使用子查询时,UNION 字会出现语法错误。

我可以将 Update 查询与 Union 语句混合使用吗?或者也许我必须使用两个查询来获得我的成就?任何帮助将不胜感激。

4

1 回答 1

2

UNION不适用于子查询,但适用于查询。SELECT只需省略两个s周围的括号。

您应该能够将整个查询SELECT ... UNION SELECT ...用作子查询,然后将其括在括号中。

order by不能用于联合的单个查询,而只能用于联合的结果。因此以下方法不起作用:

UPDATE bby_venta_co SET tupla_usada = 1 WHERE id in(
    SELECT id FROM bby_venta_co WHERE nom_agrupacion = 'CAFE NESCAFE' 
    AND promocion_id = 100000189 
    AND ticket_id = 156 
    AND fondo_fijo_id = 14 
    AND caja_id = 1 ORDER BY costo DESC LIMIT 1
    UNION ALL
    SELECT id FROM bby_venta_co WHERE nom_agrupacion = 'CAFE INTERNA' 
    AND promocion_id = 100000189 
    AND ticket_id = 156 
    AND fondo_fijo_id = 14 
    AND caja_id = 1 ORDER BY costo DESC LIMIT 1
); 

由于您在这里只使用两个单个值,因此两个子选择OR应该可以工作,完全避免UNION

UPDATE bby_venta_co SET tupla_usada = 1 WHERE id =
    (SELECT id FROM bby_venta_co WHERE nom_agrupacion = 'CAFE NESCAFE' 
    AND promocion_id = 100000189 
    AND ticket_id = 156 
    AND fondo_fijo_id = 14 
    AND caja_id = 1 ORDER BY costo DESC LIMIT 1)
  OR id =
    (SELECT id FROM bby_venta_co WHERE nom_agrupacion = 'CAFE INTERNA' 
    AND promocion_id = 100000189 
    AND ticket_id = 156 
    AND fondo_fijo_id = 14 
    AND caja_id = 1 ORDER BY costo DESC LIMIT 1)
; 
于 2013-08-29T22:24:12.307 回答