Warning: Creating default object from empty value in /www/htdocs/v030397/mysql-qotd/wp-content/plugins/sitepress-multilingual-cms/sitepress.class.php on line 4991

Warning: Creating default object from empty value in /www/htdocs/v030397/mysql-qotd/wp-content/plugins/sitepress-multilingual-cms/sitepress.class.php on line 4993
Question 41: Which of the queries is the most efficient? – MySQL Question of the Day

Skip to content

By urs in mysql questions

 

-- 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 ]

Tags: , ,

Comment Feed

One Response


  1.  
    Answer:
     
    b
     
    b reads the table only once – a and c read it 3 times to get the result.
     

You must be logged in to post a comment.