MySQL - 基于 SELECT Query 的 UPDATE 查询

MySQL - UPDATE query based on SELECT Query(MySQL - 基于 SELECT Query 的 UPDATE 查询)
本文介绍了MySQL - 基于 SELECT Query 的 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

然后我加入他们:

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

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

推荐答案

您实际上可以通过以下两种方式之一:

You can actually do this one of two ways:

MySQL 更新连接语法:

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 语法:

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.

这篇关于MySQL - 基于 SELECT Query 的 UPDATE 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)