mySQL DISTINCT和JOINS

时间:2015-06-08 19:14:47

标签: mysql join group-by distinct

QUERY

SELECT DISTINCT(o.id) as `order_line`,
  `k`.`short_name` AS `market`,
  `jc`.`code` AS `job_status`,
  `j`.`order_number` AS `job_number`,
  CONCAT('ML', `l`.`supp`) AS `supp_number`,
  `jd`.`needed_by` AS `needed_by`,
  `jd`.`mastec_onjob` AS `mastec_onjob`,
  `jd`.`revised_crcd` AS `revised_crcd`,
  `e`.`lastname` AS `install supervisor`,
  `o`.`order_number` AS `po number`,
  `o`.`order_date` AS `ordered`,
  `o`.`qty_ordered` AS `qty_ordered`,
  `o`.`ship_date` AS `vendor ship`,
  `o`.`rcvd_date` AS `rcvd_date`,
  `o`.`qty_received` AS `qty_received`,
  `m`.`mastec_partno` AS `mastec_partno`,
  `v`.`long_name` AS `vendor_name`,
  `o`.`mm_notes` AS `mm_notes`,
  `o`.`pm_notes` AS `pm_notes`,
  `o`.`rc_notes` AS `rc_notes` 
FROM
  mm_orders as o 
  LEFT JOIN `material_lists` `l` 
    ON ((`l`.`id` = `o`.`ml_id`)) 
  LEFT JOIN `jobs` `j` 
    ON ((`l`.`job_id` = `j`.`id`)) 
  LEFT JOIN `clli` `c` 
    ON ((`j`.`clli` = `c`.`id`)) 
  LEFT JOIN `markets` `k` 
    ON ((`k`.`id` = `c`.`market`)) 
  LEFT JOIN `employees` `e` 
    ON ((`e`.`employee_number` = `j`.`install_supervisor`)) 
  LEFT JOIN `job_dates` `jd` 
    ON ((`l`.`job_id` = `jd`.`job_id`)) 
  LEFT JOIN `mat_r12` `m` 
    ON ((`o`.`ci_id` = `m`.`id`)) 
  LEFT JOIN `vendors` `v` 
    ON ((`v`.`id` = `m`.`vendor_id`)) 
  LEFT JOIN `ml_contents` `mc` 
    ON ((`l`.`id` = `mc`.`ml_id`)) 
  LEFT JOIN `job_status_codes` `jc` 
    ON ((`j`.`status` = `jc`.`id`)) 
WHERE o.qty_ordered > o.qty_received 
  AND `j`.`status` IN (1, 5, 8, 11, 12, 13, 14)
  AND `mc`.`mastec_stock` = 0 
ORDER BY `j`.`order_number`,
  `l`.`id`,
  `l`.`supp`,
  `o`.`vendor_id`;

我希望结果只反映每o.id行,但这根本不是我得到的。当我删除GROUP BY时,我得到63391行,并且在那里,我只获得188行。当我运行SELECT id FROM mm_orders WHERE qty_ordered > qty_received时,我在1249获得了正确的行数。显然,我不是我认为的 MySQL 大师。是我的JOIN还是我只是将查询从一端完全篡改到另一端?

如果层次结构不清楚,从上到下:job-> material_list-> ml_contents。可以为多个material_lists分配相同的job_id,多个ml_contents位于同一个material_list内。下表具有一对一的关系:job-> job_dates,ml_contents-> mm_orders。所有其他的都应该是不言自明的,但如果 MySQL 有一个很好的 jsFiddle 类型的工具,我很乐意发布每个表的结构。

QUERY UPDATED

1 个答案:

答案 0 :(得分:0)

这是联接。您使用了内部联接,但也许某些订单没有材料列表或安装程序或其他任何内容。这些订单不会在最终结果中,导致它下降到188个唯一订单。

此外,如果订单的作业有多个作业日期,您将在每个作业日期的结果中获得该订单。这将导致188个唯一订单的最终结果显示为63391行。

因此,您应该先问自己想要查询的是什么,而不是应用分组和区别来尝试解决它。您想要一份独特的订单清单,还是想要额外的信息?如果是后者,请注意查询包含例如订单行或作业日期,并且订单信息本身可能会重复。