I have 2 queries that show month to date totals. I need to loop through them so they end up in the same table. Is it possible to combine the WHILE or combine the queries to have the ORDERS alternate?
$MTDcurrent = $db->Execute("SELECT SUM(order_total) AS MTDC, month(date_purchased) AS Months FROM " . TABLE_ORDERS ."
WHERE orders_status IN(1,2,3,100,101,103,105) AND date(date_purchased) BETWEEN DATE_FORMAT(current_date,'%Y-01-01') AND current_date GROUP BY Months ASC LIMIT 10 ");
$MTDprevious = $db->Execute("SELECT SUM(order_total) AS MTDP, month(date_purchased) AS Months FROM " . TABLE_ORDERS ."
WHERE orders_status IN(1,2,3,100,101,103,105) AND date(date_purchased) BETWEEN DATE_FORMAT(date_sub(current_date, INTERVAL 1 year),'%Y-01-01') AND date_sub(current_date, INTERVAL 1 year)
GROUP BY Months ASC LIMIT 10 ");
Thanks in Advance
You can do this directly with while loop like this:
while( ($row = array_shift( $MTDcurrent)) || ($row = array_shift( $MTDprevious))){
$row = 'your data';
}
However I don't consider this clean and obvious way. You may rather merge arrays with array_merge
(if there's no large amount of data):
foreach( array_merge( $MTDcurrent, $MTDprevious) as $row){
$row = 'your data';
}
And if your code is performance critical and will use large amount of data you should implement Iterator
with next
function like this:
public function next() {
$this->row = mysql_fetch_assoc( $this->query);
if( $this->row){
return;
}
if( count( $this->queries)){
$this->query = mysql_query( array_shift( $this->queries));
$this->next();
}
}
Warning: this is just an idea, not whole implementation you should rely on!
EDIT blah, I got question wrong, you're looking for mysql UNION
statement .
This is a slightly different approach avoiding the multiple queries. I have not tried it as I do not have an RDBMS on the machine I am using right now but it should be close enough -
SELECT
SUM(order_total) AS MTDP,
month(date_purchased) AS Months,
year(date_purchased) AS Years
FROM orders
WHERE orders_status IN(1,2,3,100,101,103,105)
AND DATE(date_purchased) > DATE_FORMAT(DATE_SUB(CURRENT_DATE, INTERVAL 1 year),'%Y-01-01')
GROUP BY Years, Months
ORDER BY Months ASC, Years ASC
In your response to your comment - you could modify the date part of the WHERE clause to be a combination of your two WHERE clauses
AND (
(date(date_purchased) BETWEEN DATE_FORMAT(current_date,'%Y-01-01') AND current_date)
OR
(date(date_purchased) BETWEEN DATE_FORMAT(date_sub(current_date, INTERVAL 1 year),'%Y-01-01') AND date_sub(current_date, INTERVAL 1 year))
)
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.