如何合并具有不同日期的两个表并加入另一个表?

时间:2019-06-17 13:34:24

标签: mysql laravel laravel-5 eloquent

我目前正在尝试使用Laravel / Eloquent执行查询,但是我决定首先编写SQL查询,以便找出问题所在。 我想按日期分组并使用多个联接合并两个表的结果,但是当我像这样添加product_metrics表时,结果会出错:

inner join `product_metrics` on `products`.`id` = `product_metrics`.`product_id`

Database Schema

select
  date_format(`date` + INTERVAL 1 HOUR, '%Y-%m-%d') as day,
  round(sum(`item_price` * `quantity_ordered`), 2) as sales,
  sum(`quantity_ordered`) as units,
  sum(
    CASE
      WHEN `is_refund` THEN `item_price` * `quantity_ordered`
      ELSE 0
    END
  ) as refunds,
  sum(
    CASE
      WHEN `is_refund` THEN `quantity_ordered`
      ELSE 0
    END
  ) as refund_units,
  sum(`promotion_discount`) as discounts,
  sum(`sessions`) as sessions,
  count(DISTINCT(customer_order_id)) as orders,
  round(sum(`product_sales`), 2) as sales_sc,
  round(
    sum(`unit_session_percentage` * `product_sales`) / sum(`product_sales`),
    2
  ) as cvr,
  sum(`page_views`) as views

from
  `products`
  inner join `product_brands` on `products`.`brand_id` = `product_brands`.`id`
  inner join `customer_order_items` on `products`.`id` = `customer_order_items`.`product_id`
  inner join `customer_orders` on `customer_order_items`.`customer_order_id` = `customer_orders`.`id`
  inner join `product_metrics` on `products`.`id` = `product_metrics`.`product_id`
  inner join `customers` on `products`.`customer_id` = `customers`.`id`
  inner join `marketplaces` on `products`.`marketplace_id` = `marketplaces`.`id`
  where
  (
    `date` between "2019-05-01 00:00:00"
    and "2019-05-31 00:00:00"
    or `purchase_date` between "2019-05-01 00:00:00"
    and "2019-05-31 00:00:00"
    and `customers`.`id` = 18
  )
  and `products`.`deleted_at` is null
group by
  date_format(`date` + INTERVAL 1 HOUR, '%Y-%m-%d')
order by
  `day` asc

我想要/需要做的是: 使用where子句查询products,并添加日期以获取给定时间段内与这些产品相关的所有product_metrics和所有customer_orders

3 个答案:

答案 0 :(得分:0)

你是说...

              date between "2019-05-01 00:00:00" and "2019-05-31 00:00:00"
or ( purchase_date between "2019-05-01 00:00:00" and "2019-05-31 00:00:00"
 and customers.id = 18)

此外,如果您为表加上别名并使用这些别名限定列,那么操作起来会容易得多。

答案 1 :(得分:0)

我的猜测是您缺少括号以确保OR优先处理。

A or B and C ==> A or ( B and C )

您可能想要

( A or B ) and C

所以

where
(
  (    `date` between "2019-05-01 00:00:00" and "2019-05-31 00:00:00"
    or `purchase_date` between "2019-05-01 00:00:00" and "2019-05-31 00:00:00"
  )
  and `customers`.`id` = 18
)

答案 2 :(得分:0)

考虑到产品和指标之间的一对多关系,这是预期的。