转换不存在到另一个使用join的查询

时间:2013-03-26 08:42:50

标签: mysql

这是使用不存在的查询.. 任何人都可以使用join重写此查询吗?

SELECT name,
       trans
FROM skyplan_deploy.deploy_stars d
WHERE apt='KOPF'
  AND name!=trans
  AND NOT EXISTS
    (SELECT DISTINCT c.star_ident,
                     c.fix_ident
     FROM corept.std_star_leg c
     INNER JOIN
       (SELECT star_ident,
               transition_ident,
               max(sequence_num) seq,
               route_type
        FROM corept.std_star_leg
        WHERE data_supplier='J'
          AND airport_ident='KOPF'
        GROUP BY star_ident,
                 transition_ident)b ON c.sequence_num=b.seq
     AND c.star_ident=b.star_ident
     AND c.transition_ident=b.transition_ident
     WHERE c.data_supplier='J'
       AND c.airport_ident='KOPF'
       AND d.name=c.star_ident
       AND d.trans=c.fix_ident);

谢谢

让corept.std_star_leg表成为这样。

star_ident transition_ident sequence_num fix_ident airport
A               XX               10         QWE     KOPF  
A               XX               20         WER     KOPF  
A               XX               30         HYU     KOPF  
A               XX               40         GJI     KOPF   
B               YY               10         SJI     KOPF  
B               YY               20         DJI     KOPF  
B               YY               30         FJI     KOPF  
B               YY               40         GHI     KOPF  
B               YY               50         KDI     KOPF 

执行内连接后,结果将如下获得。

A               XX               40         GJI  
B               YY               50         KDI  

从而检索max sequence_num行。之后,skyplan_deploy.deploy_stars表将如下所示。

apt            name              trans  
KOPF            A                 GJI  
KOPF            A                 FJI  
KOPF            A                 DHI  
KOPF            B                 KDI  
KOPF            B                 VNM  

我需要输出

A  FJI  
A  DHI  
B  VNM

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT NAME, trans
FROM skyplan_deploy.deploy_stars d
Left Join
(
        SELECT DISTINCT c.star_ident, c.fix_ident
        FROM corept.std_star_leg c
        INNER JOIN (
            SELECT star_ident, transition_ident, max(sequence_num) seq, route_type
            FROM corept.std_star_leg
            WHERE data_supplier = 'J' AND airport_ident = 'KOPF'
            GROUP BY star_ident, transition_ident
            ) b
            ON c.sequence_num = b.seq AND c.star_ident = b.star_ident AND c.transition_ident = b.transition_ident
        WHERE c.data_supplier = 'J' AND c.airport_ident = 'KOPF' 
)tbl
On d.NAME = tbl.star_ident AND d.trans = tbl.fix_ident
Where tbl.star_ident Is Null