如何在MYSQL中将条件内部查询转换为LEFT JOIN?

时间:2016-11-03 10:33:06

标签: mysql sql

我有这样的查询

SELECT * FROM CC 
INNER JOIN App (CC.id = App.id)   
WHERE CC.counter >1000
AND 0 = IF(CC.key1 = App.key1,
                    (SELECT COUNT(*)
                        FROM Service
                        WHERE App.No = Service.No
                     )
                    ),
                    (SELECT COUNT(*)
                        FROM Service
                        WHERE App.NoCo = Service.No
                        AND App.NoCo != ''
                      )
                    )
                )

如何在MYSQL中将条件内部查询转换为LEFT JOIN?

我正在尝试将此子查询转换为join子句以获得更好的性能

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT * FROM CC 
INNER JOIN App (CC.id = App.id)   
LEFT JOIN(SELECT s.no,count(*) as cnt_1,sum(s.no <> '') as cnt_2
          FROM Service s
          GROUP BY s.no) t
 ON(0 = CASE WHEN CC.key1 = App.key1 THEN t.cnt_1 ELSE t.cnt_2 END)
WHERE CC.counter >1000

答案 1 :(得分:1)

我会改用EXISTS

SELECT *
FROM CC INNER JOIN
     App
     ON CC.id = App.id 
WHERE CC.counter > 1000 AND
      ( (CC.key1 = App.key1 AND
         NOT EXISTS (SELECT 1
                     FROM Service
                     WHERE App.No = Service.No
                    ) OR
        (CC.key1 = App.key1 AND
         NOT EXISTS (SELECT 1
                     FROM Service
                     WHERE App.NoCo = Service.No AND
                           App.NoCo <> ''
                    )
         )
        );

为了提高性能,您需要Service(No)CC(counter, id)上的索引。

您必须小心使用LEFT JOIN,因为您的条件为OR。这可能会无意中增加行数。