MySQL - 基于SELECT Query的UPDATE查询

时间:2009-08-11 20:39:41

标签: mysql select sql-update

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

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

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

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

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查询吗?

12 个答案:

答案 0 :(得分:712)

您实际上可以采用以下两种方式之一:

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)

选择对你来说最自然的一个。

答案 1 :(得分:264)

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

希望这适合你。

答案 2 :(得分:94)

在MySQL中很容易:

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

答案 3 :(得分:49)

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

对于所有级别,这个更好更干净:

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!它很棒!

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

希望它有效,如果不让我知道。我会为你写一个确切的查询。

答案 4 :(得分:13)

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 ;

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

答案 5 :(得分:11)

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

我需要在活动表中填充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中,所以我创建了一个临时表,并将其与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;

我希望有人发现这个有用的

答案 6 :(得分:6)

private void copyAssets() {
    AssetManager assetManager = mContext.getAssets();
    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open("database_copy.db");
        String currentDBPath = "/data/data/com.example.somepackagename/databases/books-db";
        out = new FileOutputStream(currentDBPath);
        copyFile(in, out);
        in.close();
        out.flush();
        out.close();
    } catch(IOException e) {

        Log.e("tag", "Failed to copy asset file " , e);
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}

答案 7 :(得分:4)

您可以使用内部联接更新其他表中的值,如此

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 as子查询来执行此操作

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/

答案 8 :(得分:3)

您可以使用:

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

答案 9 :(得分:3)

对于同一张桌子,

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;

答案 10 :(得分:1)

检查以下查询。

更新表A A A.name_a上的内部联接表B B = B.name_b 设置validation_check = if(start_dts> end_dts,'VALID','')

答案 11 :(得分:0)

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

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