MySQL-ACTUALIZAR consulta basada en la consulta SELECT


Necesito comprobar (desde la misma tabla) si hay una asociación entre dos eventos basados en fecha-hora.

Un conjunto de datos contendrá la fecha-hora de finalización de ciertos eventos y el otro conjunto de datos contendrá la fecha-hora de inicio de otros eventos.

Si el primer evento se completa antes del segundo evento, me gustaría vincularlos.

Lo que tengo hasta ahora es:

SELECT name as name_A, date-time as end_DTS, id as id_A 
FROM tableA WHERE criteria = 1


SELECT name as name_B, date-time as start_DTS, id as id_B 
FROM tableA WHERE criteria = 2

Entonces me uno a ellos:

SELECT name_A, name_B, id_A, id_B, 
if(start_DTS > end_DTS,'VALID','') as validation_check
FROM tableA
LEFT JOIN tableB ON name_A = name_B

Puedo entonces, basado en mi validation_check campo, ejecutar una consulta de ACTUALIZACIÓN con el SELECCIONAR anidado?

Author: linuxbuild, 2009-08-12

12 answers

Puedes hacer esto de dos maneras:

MySQL update join sintaxis:

update tableA a
inner join tableB b on a.name_a = b.name_b
set validation_check = if(start_dts > end_dts, 'VALID', '')
-- where clause can go here

Sintaxis de ANSI SQL:

update tableA set validation_check = 
    (SELECT if(start_DTS > end_DTS,'VALID','') as validation_check
        FROM tableA
        INNER JOIN tableB ON name_A = name_B
        WHERE id_A = tableA.id_A)

Elige el que te parezca más natural.

 642
Author: Eric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 21:19:02
UPDATE
    `table1` AS `dest`,
    (
        SELECT
            *
        FROM
            `table2`
        WHERE
            `id` = x
    ) AS `src`
SET
    `dest`.`col1` = `src`.`col1`
WHERE
    `dest`.`id` = x
;

Espero que esto funcione para usted.

 233
Author: massquote,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-20 09:53:21

Fácil en MySQL:

UPDATE users AS U1, users AS U2 
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id
 79
Author: Sergio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-06 10:06:19

Si alguien está buscando actualizar datos de una base de datos a otra sin importar a qué tabla se dirige, debe haber algunos criterios para hacerlo.

Este es mejor y limpio para todos los niveles:

update dbname1.content targetTable

left join dbname2.someothertable sourceTable on
    targetTable.compare_field= sourceTable.compare_field
set
    targetTable.col1  = sourceTable.cola
    ,targetTable.col2 = sourceTable.colb 
    ,targetTable.col3 = sourceTable.colc 
    ,targetTable.col4 = sourceTable.cold 

Traaa! ¡Funciona muy bien!

Con la comprensión anterior, puede modificar los campos establecidos y los criterios "on" para hacer su trabajo. También puede realizar las comprobaciones, luego extraer los datos en las tablas temporales y luego ejecutar la actualización utilizando la sintaxis anterior reemplazando la tabla y nombres de columnas.

Espero que funcione, si no házmelo saber. Voy a escribir una pregunta exacta para usted.

 44
Author: KMX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-04 12:11:51

Encontré esta pregunta en la búsqueda de mi propia solución a un join muy complejo. Esta es una solución alternativa, a una versión más compleja del problema, que pensé que podría ser útil.

Necesitaba rellenar el campo product_id en la tabla actividades, donde las actividades están numeradas en una unidad, y las unidades están numeradas en un nivel (identificado usando una cadena ??N), de tal manera que uno puede identificar actividades usando un SKU ie L1U1A1. Esos SKU se almacenan en una tabla diferente.

Identifiqué lo siguiente para obtener una lista de activity_id vs product_id: -

SELECT a.activity_id, w.product_id 
FROM activities a 
JOIN units USING(unit_id) 
JOIN product_types USING(product_type_id) 
JOIN web_products w 
  ON sku=CONCAT('L',SUBSTR(product_type_code,3), 'U',unit_index, 'A',activity_index)

Encontré que eso era demasiado complejo para incorporarlo en un SELECT dentro de mysql, así que creé una tabla temporal, y la uní con la instrucción update: -

CREATE TEMPORARY TABLE activity_product_ids AS (<the above select statement>);

UPDATE activities a JOIN activity_product_ids b ON a.activity_id=b.activity_id 
  SET a.product_id=b.product_id;

Espero que alguien encuentre esto útil

 11
Author: sibaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-15 14:39:33
UPDATE 
  receipt_invoices dest,
  (
    SELECT 
      `receipt_id`,
      CAST((net * 100) / 112 AS DECIMAL (11, 2)) witoutvat 
    FROM
      receipt 
    WHERE CAST((net * 100) / 112 AS DECIMAL (11, 2)) != total 
      AND vat_percentage = 12
  ) src 
SET
  dest.price = src.witoutvat,
  dest.amount = src.witoutvat 
WHERE col_tobefixed = 1 
  AND dest.`receipt_id` = src.receipt_id ;

Espero que esto le ayude en un caso en el que tenga que coincidir y actualizar entre dos tablas.

 10
Author: Don,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-05 09:46:27

Puede actualizar los valores de otra tabla usando inner join como este

UPDATE [table1_name] AS t1 INNER JOIN [table2_name] AS t2 ON t1.column1_name] = t2.[column1_name] SET t1.[column2_name] = t2.column2_name];

Siga aquí para saber cómo usar esta consulta http://www.voidtricks.com/mysql-inner-join-update /

O puede usar seleccionar como subconsulta para hacer esto

UPDATE [table_name] SET [column_name] = (SELECT [column_name] FROM [table_name] WHERE [column_name] = [value]) WHERE [column_name] = [value];

Consulta explicada en detalle aquí http://www.voidtricks.com/mysql-update-from-select /

 4
Author: Anand Roshan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-15 00:52:41
UPDATE [table_name] AS T1,
      (SELECT [column_name] 
        FROM [table_name] 
        WHERE [column_name] = [value]) AS T2 
  SET T1.[column_name]=T2.[column_name] + 1
WHERE T1.[column_name] = [value];
 4
Author: bhavik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-21 05:32:56

Puedes usar:

UPDATE Station AS st1, StationOld AS st2
   SET st1.already_used = 1
 WHERE st1.code = st2.code
 2
Author: SergeyUr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-03 06:29:09

Para el mismo cuadro,

UPDATE PHA_BILL_SEGMENT AS PHA,
     (SELECT BILL_ID, COUNT(REGISTRATION_NUMBER) AS REG 
       FROM PHA_BILL_SEGMENT
        GROUP BY REGISTRATION_NUMBER, BILL_DATE, BILL_AMOUNT
        HAVING REG > 1) T
    SET PHA.BILL_DATE = PHA.BILL_DATE + 2
 WHERE PHA.BILL_ID = T.BILL_ID;
 1
Author: Gnanam pragasam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-01 16:55:43

Tuve un problema con entradas duplicadas en una tabla. A continuación se muestra los enfoques estaban trabajando para mí. También ha sido defendido por @ sibaz.

Finalmente lo resolví usando las siguientes consultas:

  1. La consulta select se guarda en una tabla temporal

    IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') IS NOT NULL
        DROP TABLE #New_format_donor_temp;
    
    select *
    into #New_format_donor_temp
    from DONOR_EMPLOYMENTS
    where DONOR_ID IN (
      1, 2
    )
    
    -- Test New_format_donor_temp
    -- SELECT *
    -- FROM #New_format_donor_temp;
    
  2. La tabla temp se une en la consulta update.

    UPDATE de
    SET STATUS_CD=de_new.STATUS_CD, STATUS_REASON_CD=de_new.STATUS_REASON_CD, TYPE_CD=de_new.TYPE_CD
    FROM DONOR_EMPLOYMENTS AS de
      INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO
    WHERE
      de.DONOR_ID IN (
        3, 4
    )
    

No tengo mucha experiencia con SQL, por favor, aconseje cualquier mejor enfoque que conozca.

Las consultas anteriores son para MySQL servidor.

 0
Author: Rick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 08:13:55

Compruebe con la siguiente consulta.

Actualizar tablaA A tabla de unión interna B en A. name_a = B. name_b set validation_check = if (start_dts > end_dts, 'VALID', ")

 0
Author: Anoop Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 11:16:17