SQL中的嵌套查询

时间:2017-11-16 11:37:48

标签: 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

Basily 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

如果您有任何建议我会非常感激

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询来获得答案。

SELECT distinct de.MCH_CODE 
FROM table1 AS de 
join table2 as md ON de.subcode = md.subcode WHERE de.ShortenCode 
in
(
    select Table2.ShortenCode from
    (
       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
    ) Table2
)

答案 1 :(得分:0)

我认为您可以尝试像这样在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

尽管我猜测取决于索引和数据量,但计算可能需要很长时间。