删除相关的子查询

时间:2016-01-06 09:06:54

标签: mysql sql

您可以帮我优化查询吗?我们使用相关的子查询来解决我们的问题。如何提高性能并删除相关的子查询。

SELECT CAST((CASE WHEN value = 1
  THEN CASE WHEN (SELECT COUNT(records)
                  FROM ABC
                  WHERE ABC.ID = XYZ.ID) > 0
    THEN 1
       ELSE 0 END
             ELSE CASE WHEN (SELECT COUNT(records)
                             FROM PQR
                             WHERE PQR.ID = XYZ.ID) > 0
               THEN 1
                  ELSE 0 END END) AS AA) AS COLUMN FROM XYZ

2 个答案:

答案 0 :(得分:2)

试试这个。我已将子查询移到分隔的临时表中。

SELECT XYZ.id, 
        CASE WHEN XYZ.value = 1
             THEN CASE WHEN T.cnt > 0 THEN 1 ELSE 0 END
             ELSE CASE WHEN T2.cnt > 0 THEN 1 ELSE 0 END
             END as column
FROM XYZ
    LEFT JOIN ( SELECT id, COUNT(*) AS cnt FROM ABC 
                GROUP BY id) AS T ON XYZ.id = T.id
    LEFT JOIN ( SELECT id, COUNT(*) AS cnt FROM PQR
                GROUP BY id) AS T2 ON XYZ.id = T2.id
GROUP BY XYZ.id

另一种解决方案。只需检查ABC和PQR表中的存在ID。感谢评论员。

SELECT XYZ.id,
       CASE WHEN XYZ.value = 1
            THEN T.id IS NOT NULL
            ELSE T2.id IS NOT NULL
            END AS column
FROM XYZ
   LEFT JOIN (SELECT DISTINCT id FROM ABC) AS T ON XYZ.id = T.id
   LEFT JOIN (SELECT DISTINCT id FROM PQR) AS T2 ON XYZ.id = T2.id

答案 1 :(得分:1)

你应该尽量避免在这里使用COUNT,你不必关心每种情况下有多少行,只要他们是EXIST还是{。}}。

MySQL中的布尔条件分别为10返回TRUEFALSE,因此您可以节省相当多的语法。

我认为这就是你想要的,大大简化了:

SELECT (x.value  =1 AND EXISTS (SELECT 1 FROM ABC a WHERE a.id = x.id))
         OR 
       (x.value !=1 AND EXISTS (SELECT 1 FROM PQR p WHERE p.id = x.id)) column
  FROM XYZ x

或可能:

SELECT EXISTS (SELECT 1 FROM ABC a WHERE a.id = x.id) column
  FROM XYZ x
 WHERE x.value = 1
 UNION ALL
SELECT EXISTS (SELECT 1 FROM PQR p WHERE p.id = x.id)
  FROM XYZ x
 WHERE x.value != 1

或者如果你喜欢的话:

   SELECT CASE 
            WHEN x.value = 1 THEN EXISTS (SELECT 1 FROM ABC a WHERE a.id = x.id)
            ELSE EXISTS (SELECT 1 FROM PQR p WHERE p.id = x.id)
          END column
     FROM XYZ x