MySQL - 基于 SELECT 查询的 UPDATE 查询

发布于 2024-08-01 18:24:34 字数 606 浏览 2 评论 0原文

我需要检查(从同一张表)两个事件之间是否存在基于日期时间的关联。

一组数据将包含某些事件的结束日期-时间,另一组数据将包含其他事件的开始日期-时间。

如果第一个事件在第二个事件之前完成,那么我想将它们链接起来。

到目前为止我所拥有的是:

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

然后我加入他们:

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

然后我可以根据我的validation_check字段,使用嵌套的SELECT运行UPDATE查询吗?

I need to check (from the same table) if there is an association between two events based on date-time.

One set of data will contain the ending date-time of certain events and the other set of data will contain the starting date-time for other events.

If the first event completes before the second event then I would like to link them up.

What I have so far is:

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

Then I join them:

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

Can I then, based on my validation_check field, run a UPDATE query with the SELECT nested?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

岁月静好 2024-08-08 18:24:34

实际上,您可以通过以下两种方式之一执行此操作:

MySQL 更新连接语法:

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

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)

选择您认为最自然的一种。

You can actually do this one of two ways:

MySQL update join syntax:

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

ANSI SQL syntax:

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)

Pick whichever one seems most natural to you.

江湖正好 2024-08-08 18:24:34
UPDATE
    `table1` AS `dest`,
    (
        SELECT
            *
        FROM
            `table2`
        WHERE
            `id` = x
    ) AS `src`
SET
    `dest`.`col1` = `src`.`col1`
WHERE
    `dest`.`id` = x
;

希望这对你有用。

UPDATE
    `table1` AS `dest`,
    (
        SELECT
            *
        FROM
            `table2`
        WHERE
            `id` = x
    ) AS `src`
SET
    `dest`.`col1` = `src`.`col1`
WHERE
    `dest`.`id` = x
;

Hope this works for you.

哭了丶谁疼 2024-08-08 18:24:34

在 MySQL 中很容易:

UPDATE users AS U1, users AS U2 
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id

Easy in MySQL:

UPDATE users AS U1, users AS U2 
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id
独自唱情﹋歌 2024-08-08 18:24:34
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];
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];
醉梦枕江山 2024-08-08 18:24:34

您可以使用内部联接更新另一个表中的值,如下

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];

所示 按照此处了解如何使用此查询 http://www.voidtricks.com/mysql-inner-join-update/

或者您可以使用 select 作为子查询来执行此

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

查询,详细说明如下http://www.voidtricks.com/mysql-update-from-select/

You can update values from another table using inner join like this

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];

Follow here to know how to use this query http://www.voidtricks.com/mysql-inner-join-update/

or you can use select as subquery to do this

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

query explained in details here http://www.voidtricks.com/mysql-update-from-select/

夏夜暖风 2024-08-08 18:24:34

如果有人寻求将数据从一个数据库更新到另一个数据库,无论他们针对哪个表,都必须有一些标准来执行此操作。

这个对于所有级别来说都更好、更干净:

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! 效果很好!

有了上述理解,您就可以修改设置的字段和“on”条件来完成您的工作。 您还可以执行检查,然后将数据拉入临时表,然后使用上述语法替换表和列名称来运行更新。

希望它有效,如果不行请告诉我。 我将为您写一个精确的查询。

If somebody is seeking to update data from one database to another no matter which table they are targeting, there must be some criteria to do it.

This one is better and clean for all levels:

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! It works great!

With the above understanding, you can modify the set fields and "on" criteria to do your work. You can also perform the checks, then pull the data into the temp table(s) and then run the update using the above syntax replacing your table and column names.

Hope it works, if not let me know. I will write an exact query for you.

泪冰清 2024-08-08 18:24:34
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 ;

希望这在您必须在两个表之间进行匹配和更新的情况下对您有所帮助。

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 ;

Hope this will help you in a case where you have to match and update between two tables.

江心雾 2024-08-08 18:24:34

我在寻找自己的非常复杂的连接解决方​​案时发现了这个问题。 这是问题的更复杂版本的替代解决方案,我认为这可能有用。

我需要填充活动表中的product_id 字段,其中活动以单位编号,单位以级别编号(使用字符串??N 标识),以便可以使用 SKU(即 L1U1A1)识别活动。 然后,这些 SKU 存储在不同的表中。

我确定了以下内容来获取 Activity_id 与 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)

我发现这太复杂,无法合并到 mysql 中的 SELECT 中,因此我创建了一个临时表,并将其与更新语句连接起来:-

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;

我希望有人找到这个有用

I found this question in looking for my own solution to a very complex join. This is an alternative solution, to a more complex version of the problem, which I thought might be useful.

I needed to populate the product_id field in the activities table, where activities are numbered in a unit, and units are numbered in a level (identified using a string ??N), such that one can identify activities using an SKU ie L1U1A1. Those SKUs are then stored in a different table.

I identified the following to get a list of 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)

I found that that was too complex to incorporate into a SELECT within mysql, so I created a temporary table, and joined that with the update statement:-

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;

I hope someone finds this useful

仅此而已 2024-08-08 18:24:34

对于同一张表,

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;

For same table,

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;
ぶ宁プ宁ぶ 2024-08-08 18:24:34

您可以使用:

UPDATE Station AS st1, StationOld AS st2
   SET st1.already_used = 1
 WHERE st1.code = st2.code

You can use:

UPDATE Station AS st1, StationOld AS st2
   SET st1.already_used = 1
 WHERE st1.code = st2.code
彼岸花ソ最美的依靠 2024-08-08 18:24:34

我遇到了一个表本身重复条目的问题。 以下是对我有用的方法。 @sibaz 也提倡这样做。

最后我使用以下查询解决了这个问题:

  1. 选择查询保存在临时表中

    IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') 不为空 
          删除表#New_format_donor_temp; 
    
      选择 * 
      进入#New_format_donor_temp 
      来自 DONOR_EMPLOYMENTS 
      其中 DONOR_ID IN ( 
        1, 2 
      ) 
    
      -- 测试 New_format_donor_temp 
       -  选择 * 
      -- 来自#New_format_donor_temp; 
      
  2. 临时表连接到更新查询中。

    更新德 
      设置 STATUS_CD=de_new.STATUS_CD、STATUS_REASON_CD=de_new.STATUS_REASON_CD、TYPE_CD=de_new.TYPE_CD 
      FROM DONOR_EMPLOYMENTS 作为 de 
        INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO 
      在哪里 
        de.DONOR_ID IN ( 
          3, 4 
      ) 
      

我对 SQL 不太有经验,请告知您知道的更好的方法。

以上查询是针对 MySql 服务器的。

I had an issue with duplicate entries in one table itself. Below is the approaches were working for me. It has also been advocated by @sibaz.

Finally I solved it using the below queries:

  1. The select query is saved in a temp table

    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. The temp table is joined in the update query.

    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
    )
    

I not very experienced with SQL please advise any better approach you know.

Above queries are for MySql server.

弱骨蛰伏 2024-08-08 18:24:34

如果您要从复杂的查询中进行更新。 最好的办法是从查询创建临时表,然后使用临时表作为一个查询进行更新。

    DROP TABLE IF EXISTS cash_sales_sums;
CREATE TEMPORARY TABLE cash_sales_sums as
SELECT tbl_cash_sales_documents.batch_key, COUNT(DISTINCT tbl_cash_sales_documents.cash_sale_number) no_of_docs,
  SUM(tbl_cash_sales_documents.paid_amount) paid_amount, SUM(A.amount - tbl_cash_sales_documents.bonus_amount - tbl_cash_sales_documents.discount_given) amount,
  SUM(A.recs) no_of_entries FROM 
        tbl_cash_sales_documents
    RIGHT JOIN(
        SELECT
            SUM(
                tbl_cash_sales_transactions.amount
            )amount,
            tbl_cash_sales_transactions.cash_sale_document_id,
            COUNT(transaction_id)recs
        FROM
            tbl_cash_sales_transactions
        GROUP BY
            tbl_cash_sales_transactions.cash_sale_document_id
    )A ON A.cash_sale_document_id = tbl_cash_sales_documents.cash_sale_id
    GROUP BY
        tbl_cash_sales_documents.batch_key
ORDER BY batch_key;





UPDATE tbl_cash_sales_batches SET control_totals = (SELECT amount FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key LIMIT 1),
expected_number_of_documents = (SELECT no_of_docs FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key),
computer_number_of_documents = expected_number_of_documents,  computer_total_amount = control_totals
WHERE batch_key IN (SELECT batch_key FROM cash_sales_sums);

if you are updating from a complex query. The best thing is create temporary table from the query, then use the temporary table to update as one query.

    DROP TABLE IF EXISTS cash_sales_sums;
CREATE TEMPORARY TABLE cash_sales_sums as
SELECT tbl_cash_sales_documents.batch_key, COUNT(DISTINCT tbl_cash_sales_documents.cash_sale_number) no_of_docs,
  SUM(tbl_cash_sales_documents.paid_amount) paid_amount, SUM(A.amount - tbl_cash_sales_documents.bonus_amount - tbl_cash_sales_documents.discount_given) amount,
  SUM(A.recs) no_of_entries FROM 
        tbl_cash_sales_documents
    RIGHT JOIN(
        SELECT
            SUM(
                tbl_cash_sales_transactions.amount
            )amount,
            tbl_cash_sales_transactions.cash_sale_document_id,
            COUNT(transaction_id)recs
        FROM
            tbl_cash_sales_transactions
        GROUP BY
            tbl_cash_sales_transactions.cash_sale_document_id
    )A ON A.cash_sale_document_id = tbl_cash_sales_documents.cash_sale_id
    GROUP BY
        tbl_cash_sales_documents.batch_key
ORDER BY batch_key;





UPDATE tbl_cash_sales_batches SET control_totals = (SELECT amount FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key LIMIT 1),
expected_number_of_documents = (SELECT no_of_docs FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key),
computer_number_of_documents = expected_number_of_documents,  computer_total_amount = control_totals
WHERE batch_key IN (SELECT batch_key FROM cash_sales_sums);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文