christian
christian

Reputation: 2489

MYSQL: Problems using COUNT and SUM functions in multi row select

I am attempting to create a procedure that selects ads from a database in rotation. And ultimately returns the selected ads row and increments the views value.

The part I am currently working on should

  1. Pull results from the 'ads' table WHERE the 'city' matches the given city and the 'spot' matches the given spot name.
  2. Add an additional 'num' column that enumerates the resulting rows.
  3. From these results, select the row where the 'num' column matches SUM('views') % COUNT(id)

This should allow me to display the ads in rotation as long as I increment the views column when an ad is ultimately selected and returned

The code I am currently working on is....

SET @t1=-1;

SELECT * 
  FROM (SELECT @t1 := @t1+1 AS num, ads.* 
          FROM ads 
         WHERE city = 'Maitland' 
           AND spot = 'home-banner' 
      ORDER BY id ASC) dt 
 WHERE dt.num = SUM(dt.views) % COUNT(dt.id);

... However I am having problems with the SUM and COUNT functions. I get an invalid use of group function error. I have also tried moving the functions to inside the sub-query, but for some reason this causes the sub-query to only return one result.

Results of Sub Query

num id  spot    city    views
0   1   home-banner Maitland    0
1   2   home-banner Maitland    2
2   3   home-banner Maitland    0
3   4   home-banner Maitland    0
4   5   home-banner Maitland    0
5   6   home-banner Maitland    0

Upvotes: 1

Views: 613

Answers (1)

Mosty Mostacho
Mosty Mostacho

Reputation: 43464

Try this:

SELECT * FROM (
  SELECT @t1 := @t1 + 1 AS num, ads.*
  FROM ads, (SELECT @t1 := -1) init
  WHERE city = 'Maitland' AND spot = 'home-banner'
  ORDER BY id ASC
) dt
WHERE dt.num = (
  SELECT SUM(views) % COUNT(id) FROM ads
  WHERE city = 'Maitland' AND spot = 'home-banner')

Upvotes: 1

Related Questions