删除重复的SQL Join结果

时间:2016-01-20 21:31:41

标签: sql postgresql

好的,我和SQL全新,所以请耐心等待。我创建了一个声明,我有我想要的结果,但想要摆脱重复的结果。什么是一个简单的解决方案?这是我的陈述

SELECT
    li.location,
    li.logistics_unit,
    li.item,
    li.company,
    li.item_desc,
    li.on_hand_qty,
    li.in_transit_qty,
    li.allocated_qty,
    li.lot,
    i.item_category3,
    location.locating_zone,
    location.location_subclass,
    i.item_category4
FROM
    location_inventory li
INNER JOIN item i ON li.item = i.item
INNER JOIN location l ON l.location = li.location
WHERE
    i.item_category3 = 'AS' AND
    li.warehouse = 'river' AND
    li.location NOT LIKE 'd%' AND
    li.location NOT LIKE 'stg%'
ORDER BY
    li.item asc

2 个答案:

答案 0 :(得分:1)

如果您对自己JOIN有信心,那么DISTINCT就应该这样做:

select DISTINCT
       location_inventory.location , 
       location_inventory.logistics_unit , 
       location_inventory.item , 
       location_inventory.company , 
       location_inventory.item_desc , 
       location_inventory.on_hand_qty , 
       location_inventory.in_transit_qty , 
       location_inventory.allocated_qty , 
       location_inventory.lot ,
       item.item_category3 , 
       location.locating_zone , 
       location.location_subclass , 
       item.item_category4
from location_inventory
INNER JOIN item
on location_inventory.item=item.item
INNER JOIN location
on location_inventory.location=location.location
where item.item_category3 = 'AS' and 
      location_inventory.warehouse = 'river' and 
      location_inventory.location not like 'd%' and 
      location_inventory.location not like 'stg%'
order by location_inventory.item asc

答案 1 :(得分:0)

假设i.item和l.location是主键或唯一键,您看到的任何重复项都是由location_inventory表中的重复项引起的。那可能是也可能不是你想要的。

SELECT DISTINCT只会消除真正的重复项(即所有选定列都重复的重复项)。如果这是你想要的,请使用它。否则,您可能需要使用SELECT DISTINCT进行内部选择以识别不需要重复的列,并将内部选择的结果连接回表以提取所有其他数据。