MySQL - 左连接+组不按预期工作

时间:2015-11-26 08:49:26

标签: mysql

所以,

我一次又一次地使用LEFT JOIN,直到现在我从来没有遇到过这个问题,我不能为我的生活做好准备!请看一下。

以下是我正在使用的表格中的一小段数据。 -

ITEM_NO  R_TYPE POS
394392      BT1 POS1
394392      BT1 POS1
394392      BT1 POS1
394392      BT1 POS1
394392      BT1 POS1
394392      BT2 POS2
394392      BT2 POS2
394392      BT2 POS2
394397      BT1 POS1
394397      BT1 POS1
394397      BT1 POS3
394397      BT1 POS3
394397      BT1 POS2
394397      BT2 POS2
394397      BT2 POS1
394397      BT2 POS1
394444      BT3 POS1

我正在尝试运行左连接查询以计算具有某些 POS 标准的不同 项目编号,并最终按<分组强> R_TYPE

Here is the SQL I have tried - 

SELECT * FROM 
          ( SELECT COUNT(DISTINCT ITEM_NO) AS CNT1, R_TYPE, 
          FROM LIVE_ITEMS WHERE AND R_TYPE LIKE 'BT%' AND
          POS NOT IN ('POS8') ) J1
           LEFT JOIN
           ( SELECT COUNT(DISTINCT ITEM_NO) AS CNT2, R_TYPE, 
          FROM LIVE_ITEMS WHERE AND R_TYPE LIKE 'BT%' AND
          POS  IN ('POS1','POS2','POS3') ) J2
          ON J1.R_TYPE= J2.R_TYPE
          GROUP BY J1.R_TYPE

如果我运行此sql,我会得到以下结果 -

CNT1    R_TYPE  CNT2    R_TYPE
137     BT1     137     BT1

这不是我想要的,我期待以下内容并且无法理解为什么......

预期数据

CNT1    R_TYPE  CNT2    R_TYPE
137     BT1     137     BT1
45      BT2     76      BT2
98      BT3     102     BT3

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

更正了您的查询。请检查。

 SELECT * FROM 
      ( SELECT COUNT(DISTINCT a.ITEM_NO) AS CNT1, a.R_TYPE 
          FROM LIVE_ITEMS a
         WHERE a.R_TYPE LIKE 'BT%' 
           AND a.POS NOT IN ('POS8')
         GROUP BY a.R_TYPE ) J1
   LEFT JOIN
       ( SELECT COUNT(DISTINCT b.ITEM_NO) AS CNT2, b.R_TYPE 
           FROM LIVE_ITEMS b
          WHERE b.R_TYPE LIKE 'BT%' 
            AND b.POS  IN ('POS1','POS2','POS3')
         GROUP BY b.R_TYPE) J2
   ON J1.R_TYPE= J2.R_TYPE
 GROUP BY J1.R_TYPE

答案 1 :(得分:1)

如果没有GROUP BY,则只有一个组,并且不确定为该组选择哪个值

  SELECT * FROM 
  ( SELECT COUNT(DISTINCT LIVE_ITEMS.ITEM_NO) AS CNT1, LIVE_ITEMS.R_TYPE, 
  FROM LIVE_ITEMS WHERE LIVE_ITEMS.R_TYPE LIKE 'BT%' AND
  LIVE_ITEMS.POS NOT IN ('POS8') GROUP BY LIVE_ITEMS.R_TYPE) J1
   LEFT JOIN
  ( SELECT COUNT(DISTINCT LIVE_ITEMS.ITEM_NO) AS CNT2, LIVE_ITEMS.R_TYPE, 
  FROM LIVE_ITEMS WHERE LIVE_ITEMS.R_TYPE LIKE 'BT%' AND
  LIVE_ITEMS.POS  IN ('POS1','POS2','POS3') GROUP BY LIVE_ITEMS.R_TYPE) J2
  AND J1.R_TYPE= J2.R_TYPE
  GROUP BY J1.R_TYPE

没有分组COUNT(DISTINCT ITEM_NO)总是会给出一个结果