mysql - SQL 中的嵌套查询

标签 mysql sql

我正在尝试使用嵌套查询组合 2 个查询。 第一个是这样的:

SELECT DISTINCT( de.MCH_CODE) AS Mach, md.MAT_CODE as ShortenCode, de.TIME as start_time
FROM table1 AS de
JOIN table1table2 AS md
ON de.subcode= md.subcode
WHERE de.ev = '123' AND de.time > '2017-11-14 07:00' and de.side = 'R' AND de.end IS NULL AND de.Subcat = 'STOP'
ORDER BY de.time

生成结果

Mach  ShortenCode  Tme  
Mach1   451         2017-12-25 08:25
Mach2   854         2017-12-25 08:25

所以 451 在 Mach1 上。棘手的部分是,对于 ShortenCode,我想显示它所在的前一个 Mach。 它会是这样的:

SELECT distinct de.MCH_CODE FROM table1 AS de
join table2 as md
ON de.subcode = md.subcode 
WHERE de.ShortenCode = 'the ones displayed in the first query'

如何通过子查询获取:

Mach  ShortenCode  Tme                 Mach(Previous)    
Mach1   451         2017-12-25 08:25   Mach4
Mach2   854         2017-12-25 08:25   Mach5

基本上 Mach 列有 Mach1,Mach2,还有 Mach4 和 Mach5。 我试过这个但没有成功:

SELECT t1.Mach, t1.ShortenCode, t1.start_time, t2.PreviousMach
    FROM( SELECT DISTINCT( de.MCH_CODE) AS Mach, md.MAT_CODE as ShortenCode, de.TIME as start_time, mch_
            FROM table1 AS de
            JOIN table1table2 AS md
            ON de.subcode= md.subcode
            WHERE de.ev = '123' AND de.time > '2017-11-14 07:00' and de.side = 'R' AND de.end IS NULL AND de.Subcat = 'STOP'
            ORDER BY de.time
    ) t1
    join
        ( SELECT distinct de.MCH_CODE FROM table1 AS de
                join table2 as md
                ON de.subcode = md.subcode 
                WHERE de.ShortenCode = t1.ShortenCode
        ) t2

如果您有任何建议,我将不胜感激

最佳答案

我想你可以尝试像这样在 SELECT 部分获取子查询

SELECT DISTINCT( de.MCH_CODE) AS Mach, md.MAT_CODE as ShortenCode, de.TIME as 
start_time,
(SELECT dee.MCH_CODE FROM table1 AS dee JOIN table1table2 AS mdd
ON dee.subcode= mdd.subcodewhere md.MAT_CODE = mdd.MAT_CODE and 
dee.MCH_CODE < de.MCH_CODE order by dee.MCH_CODE DESC LIMIT 1) as prevMach
FROM table1 AS de
JOIN table1table2 AS md
ON de.subcode= md.subcode
WHERE de.ev = '123' AND de.time > '2017-11-14 07:00' and de.side = 'R' 
AND de.end IS NULL AND de.Subcat = 'STOP'
ORDER BY de.time

尽管我猜测根据索引和数据量计算可能需要很长时间。

关于mysql - SQL 中的嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47328691/

相关文章:

mysql - 在循环中使用 mysql 准备好的语句在执行第一个循环/循环后会中断循环

mysql - 在 from 语句中插入 select 语句

sql - 如何计算多个数组中的条目数

mysql - 我无法锁定我的 MySQL 表

mysql - 在一个过程中执行插入和更新操作

java - PostgreSQLexecuteBatch() 随着时间的推移而变慢

php - 在MySQL中使用触发器插入数据库后我可以获得主键值和扩展名吗

mysql - Where 子句、列别名

mysql - Django 查询集突然不返回所有对象

java - 无法为连接 URL '' 创建类 'jdbc:mysql://localhost:3306/web13?useSSL=false&serverTimezone=UTC' 的 JDBC 驱动程序