Mysql - 加入查询没有常用列

时间:2016-04-21 14:37:23

标签: mysql join left-join jointable

我有这样的陈述:

SELECT
    COUNT(*)AS will
  FROM
    ae_orders o
  LEFT JOIN
    ae_orders_items oi ON oi.order_uid = o.uid
  WHERE
    po_date >= '2016-01-01' AND po_date <= '2016-01-31' AND status_text LIKE '%wil%'

此查询是一个计数(*),因此结果只有一个字段。 但我想一次性执行此查询6-7次,只更改此语句的(如'%will%')部分,并获得每个计数的结果。

通缉结果:

enter image description here

我尝试离开加入,像这样完全加入

(
SELECT
  COUNT(*) AS will
FROM
  ae_orders o
LEFT JOIN
  ae_orders_items oi ON oi.order_uid = o.uid
WHERE
  po_date >= '2016-01-01' AND po_date <= '2016-01-31' AND status_text LIKE '%wil%'
) AS will
LEFT JOIN
  (
  SELECT
    COUNT(*) AS will
  FROM
    ae_orders o
  LEFT JOIN
    ae_orders_items oi ON oi.order_uid = o.uid
  WHERE
    po_date >= '2016-01-01' AND po_date <= '2016-01-31' AND status_text LIKE '%phi%'
) AS phil

我不确定这是可能的。如果有人有解决方案。

解决方案

在阅读了一些评论后,我发现了另一种获取和显示数据的方法。

以下是获得解决方案的声明。

SELECT
  'Will' AS USER,
  COUNT(*) AS TOTAL
FROM
  ae_orders o
LEFT JOIN
  ae_orders_items oi ON oi.order_uid = o.uid
WHERE
  po_date >= '2016-01-01' AND po_date <= '2016-01-31' AND status_text LIKE '%wil%'
UNION
SELECT
  'Phil' AS USER,
  COUNT(*) AS TOTAL
FROM
  ae_orders o
LEFT JOIN
  ae_orders_items oi ON oi.order_uid = o.uid
WHERE
  po_date >= '2016-01-01' AND po_date <= '2016-01-31' AND status_text LIKE '%phi%'
UNION
SELECT
  'Peter' AS USER,
  COUNT(*) AS TOTAL
FROM
  ae_orders o
LEFT JOIN
  ae_orders_items oi ON oi.order_uid = o.uid
WHERE
  po_date >= '2016-01-01' AND po_date <= '2016-01-31' AND status_text LIKE '%Pet%'

而不是并排获得结果我得到的结果是一个在另一个之上。

enter image description here

1 个答案:

答案 0 :(得分:1)

如上所述,您的方案正在尝试根据条件进行调整。由于所有3个查询都是相同的日期范围,只需更改为SUM(CASE / WHEN),您将有1行包含所有3个计数。

SELECT
          SUM( case when status_text LIKE '%wil%' then 1 else 0 end ) as CountWill,
          SUM( case when status_text LIKE '%phi%' then 1 else 0 end ) as CountPhil,
          SUM( case when status_text LIKE '%Pet%' then 1 else 0 end ) as CountPeter
       from
          ae_orders o
             LEFT JOIN ae_orders_items oi 
                ON oi.order_uid = o.uid
       WHERE
              po_date >= '2016-01-01' 
          AND po_date <= '2016-01-31'