Search code examples
sqlmysqlsubquerymysql-error-1242

Can't get head round mysql subquery


Im having trouble getting my head round subqueries in Mysql. Fairly simple ones are ok, and most tutorials I find rarely go beyond the typical:

SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);

What I am trying to pull out of my database is the following (I'll try my best to explain this without any background on our db):

Retrieve list of customers belonging to particular rep and total amount spent in last month (in one column) and amount spent in month to date, in other column.

As results, this would look roughly as follows:

ID | NAME   | PREV MONTH | CUR MONTH
1  | foobar | £2300      | £1200
2  | barfoo | £1240      | £500

Query I am using to get the first part of the data is the following:

SELECT c.id,c.name, SUM(co.invoicetotal) as total
FROM customers as c
JOIN customerorders as co on co.customer_id = c.id
WHERE c.salesrep_id = 24
AND co.orderdate BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE()
GROUP by c.id
order by total desc

The DATE_SUB can be replaced by actual dates, as php variables will be going here eventually. As an example this just gives me valid data.

This gives me, for example:

ID | NAME   | TOTAL 
1  | foobar | £2300      
2  | barfoo | £1240   

So, ideally, my subquery would be this exact same query, but with the dates changed. I keep getting a #1242 - Subquery returns more than 1 row error.

Any suggestions or advice please?

Thanks in advance. Rob


Solution

  • SELECT  c.id, c.name,
            (
            SELECT  SUM(co.invoicetotal)
            FROM    customerorders co
            WHERE   co.customer_id = c.id
                    AND co.orderdate BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE()
            ) AS prev_month,
            (
            SELECT  SUM(co.invoicetotal)
            FROM    customerorders co
            WHERE   co.customer_id = c.id
                    AND co.orderdate BETWEEN CURDATE() AND CURDATE() + INTERVAL 1 MONTHS
            ) AS cur_month,
    FROM    customers as c
    WHERE   c.salesrep_id = 24
    ORDER BY
            prev_month DESC