更改子查询

时间:2016-11-10 14:31:10

标签: mysql sql performance

我得到了这样的查询,它的工作方式应该有效,但我想知道如何在一个查询中进行查询

SELECT 
(
Select count(exists)
from country c 
  join special s ON c.id_special = s.id
  join raports rap ON c.id = rap.id_raport
where c.id_document = 7 and exists = 1 
and rap.id_data = 201501 and is_id = 1
) as number_of_ID_in_table_exists,
(
 Select count(sps)
from country c 
join special s ON c.id_special = s.id
join raports rap ON c.id = rap.id_raport
where c.id_document = 7 and sps = 1 
and rap.id_data = 201501 and is_id2 = 1
 ) as number_of_ID2_in_table_exists;

2 个答案:

答案 0 :(得分:1)

使用case表达式进行条件计数:

Select count(case when exists = 1 and is_id = 1 then 1 end) as number_of_ID_in_table_exists,
       count(case when sps = 1 and is_id2 = 1 then 1 end) as number_of_ID2_in_table_exists
from country c 
  join special s ON c.id_special = s.id
  join raports rap ON c.id = rap.id_raport
where rap.id_data = 201501 and c.id_document = 7

答案 1 :(得分:1)

SELECT SUM(CASE WHEN is_id  = 1 THEN 1 END) number_of_ID_in_table_exists
       SUM(CASE WHEN is_id2 = 1 THEN 1 END) number_of_ID2_in_table_exists
FROM country c 
JOIN special s ON c.id_special = s.id
JOIN raports rap ON c.id = rap.id_raport
WHERE c.id_document = 7 AND rap.id_data = 201501 AND [exists]= 1