开发者

Filter 1 mysql row multiple ways in a php query

I'm trying to filter 1 row (sales_quantity) of a mysql table 3 different ways in a query. I want to display the same row based on the last 7 days, 30 days, and 90 days. I'm able to filter the entire query by one of these methods, but I can't figure out how to filter by 3 different methods in the same query. Thanks in advance!

Here's my code:

$sqlCommand = "SELECT 
  titles.id, 
  titles.title, 
  titles.label, 
  titles.street_date, 
  titles.upc, 
  sales.upc, 
  SUM(sales.sales_quantity) AS sum_sales, 
  sales.invoice_date 
FROM 
  titles, 
  sales 
WHERE 
  titles.upc = sales.upc 
  AND titles.label='$user_partner' 
  AND sales.invoice_date > DATE_SUB(CURDATE(), INTERVAL 90 DAY)
GROUP BY sales.upc 
ORDER BY sum_sales DESC LIMIT 30"; 

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 

$title_list = '';
while ($row = mysqli_fetch_array($query)) { 
        $title_id = $row["id"];
    $title = $row["title"];
    $title_upc = $row["upc"];
    $street_date =$row["street_date"];
    $sales_upc = $row["upc"]开发者_JS百科;
    $sales_quantity_7 = $row["sum_sales"];
        $sales_quantity_30 = $row["sum_sales"];
        $sales_quantity_90 = $row["sum_sales"];

    $title_list .= '<div class="list"><div class="title">'. $title.'</div><div class="upc">'.$title_upc.'</div><div class="date">'.$street_date.'</div><div class="sales">'.$sales_quantity_7.'</div><div class="sales">'.$sales_quantity_30.'</div><div class="sales">'.$sales_quantity_90.'</div></div>';
}
mysqli_free_result($query); 


You can join against the same table three times if you use this format. You need to create an alias for each of the sales tables and use appropriate WHERE clause criteria for each. This should work, but it's hard to be certain without a database to test myself.

EDIT: Added a fourth plain sales alias since you had other columns in there.

$sqlCommand = "SELECT 
  titles.id, 
  titles.title, 
  titles.label, 
  titles.street_date, 
  titles.upc, 
  sales.upc, 
  SUM(sales_90.sales_quantity) AS sum_sales_90,
  SUM(sales_30.sales_quantity) AS sum_sales_30,
  SUM(sales_7.sales_quantity) AS sum_sales_7,
  sales.invoice_date 
FROM 
  titles
    JOIN sales sales ON titles.upc = sales.upc
    JOIN sales sales_90 ON titles.upc = sales_90.upc
    JOIN sales sales_30 ON titles.upc = sales_30.upc
    JOIN sales sales_7 ON titles.upc = sales_7.upc
WHERE 
  AND titles.label='$user_partner' 
  AND sales_90.invoice_date > DATE_SUB(CURDATE(), INTERVAL 90 DAY)
  AND sales_30.invoice_date > DATE_SUB(CURDATE(), INTERVAL 30 DAY)
  AND sales_7.invoice_date > DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY sales.upc, sales_90.upc, sales_30.upc, sales_7.upc 
ORDER BY sum_sales_90 DESC LIMIT 30"; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜