-- test data creation create table rgen select 1 as n union select 2 union select 3 union select 4 union select 5; create table rtst select floor(rand()*3) as rt,(rand()*1000000/100) as rs from rgen a,rgen b,rgen c,rgen d,rgen e,rgen f,rgen g;
With the given tables, you would like to create a result similar to the one below:
+-------+-------+-------+ | 1nr | 2nr | 3nr | +-------+-------+-------+ | 26146 | 25874 | 26105 | +-------+-------+-------+ 1 row in set (0.13 sec)
Which of the queries is the most efficient?
a) select (select count(*) from rtst where rt=0) as 1nr, (select count(*) from rtst where rt=1) as 2nr, (select count(*) from rtst where rt=2) as 3nr; b) select sum(if(rt=0,1,0)) as 1nr, sum(if(rt=1,1,0)) as 2nr, sum(if(rt=2,1,0)) as 3nr from rtst; c) select v1.c as 1nr, v2.c as 2nr, v3.c as 3nr from (select count(*) as c from rtst where rt=0) v1, (select count(*) as c from rtst where rt=1) v2, (select count(*) as c from rtst where rt=2) v3;
[ Querying for Data (15%) - Using SELECT to Retrieve Data ]
Answer:
b
b reads the table only once – a and c read it 3 times to get the result.