简体   繁体   中英

Replacement of correlated query

I have table with name orders:

id  id_o  value  date
 1   1     400   2014-09-30 
 2   1     300   2014-09-30
 3   1     200   2014-09-30 
 4   2     100   2014-09-30  
 5   2     200   2014-09-30
 6   3     50    2014-09-29
 7   3     100   2014-09-29
 8   4     300   2014-09-29
 9   5     600   2014-09-28

I need select every order grouped by id_o with sum(value)< 700 and from this selected table i need display data grouped by datum. I use multiple select:

select date, sum(mno) as mn 
from (
   select date,sum(value) as 'mno' 
   from orders 
   group by id_o 
   having sum(value)<700
) table_alias 
group by date

This is result:

date            mn
2014-09-30      300
2014-09-29      450
2014-09-28      600

Is there any possibility to replace or to simplify this correlated query?

Your inner query is invalid. It groups by id_o , but selects by date . In order to solve this, add an additional column to the inner queries grouping (assuming date is always the same for every id_o ). You can enable strong checking by enabling the sql_mode 's ONLY_FULL_GROUP_BY . Full example in SQL fiddle .

SELECT
    date,
    SUM(mno) AS mn 
FROM (
    SELECT
        id_o,
        date,
        SUM(value) AS mno
    FROM orders
    GROUP BY
        id_o,
        date
    HAVING
        SUM(value) < 700
) totalPerOrder
GROUP BY date

MySQL allows this type of queries, but it's not common to do so. Consider the following data:

id  id_o  value  date
 1   1     400   2014-09-29 
 2   1     300   2014-09-30
 3   1     200   2014-09-30

What date (s) would SELECT date, SUM(value) FROM orders GROUP BY id_o return? It could be the first, last, average, most common one, but better make it explicit. Any other DBMS wouldn't let you execute this query.

Other than that, I would rename some of the columns to be more expressive. mn , mn_o and id_o are examples of this. Also value describes nothing, anything can be a value. Even the date field could have been called value . The query itself seems fine (take care if possibly missing indexes though).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM