灵活的搜索在数据库中查找重复项

时间:2018-06-05 19:22:56

标签: sql hybris

我有两个表 - Warehouse(id)和StockLevel(id,productCode) 商店有很多StockLevels。​​

我想在同一商店找到同一产品的StockLevel副本 例如:Warehouse" Minimarket"有两个StockLevel的产品条目" Apple"。

现在,我有这个,但我不确定它的工作方式是否正确:

select {wh.code}, {sl.productCode}, count({sl.pk}) as cnt 
from {StockLevel as sl  
left join Warehouse as wh on {sl.warehouse}={wh.pk}}  
group by ({wh.code}, {sl.productCode})
having count({sl.pk}) > 1

| id | productCode | warehouse |
--------------------------
| 1 | "apple"     | "mini" |
--------------------------
| 2 | "apple"     | "mini" |
--------------------------
| 3 | "apple"     | "maxi" |
--------------------------
| 4 | "apple"     | "macro" |
--------------------------
| 5 | "orange"    | "mini" |
--------------------------

我想要选择前两个条目中的一个(Id 1和2)(我真的不在意)。
我也有问题 - 如果我在flexibleSearch中使用此查询,我无法将其转换为实体(StockLevel)并添加{sl.pk}来查询损坏它。

1 个答案:

答案 0 :(得分:1)

如果你只想要"首先"你可以这样做:

select w.*
from warehouse w
where exists (select 1
              from warehouse w2
              where w2.warehouse = w.warehouse and w2.code = w.code and w2.id > w.id
             ) and
      not exists (select 1
                  from warehouse w2
                  where w2.warehouse = w.warehouse and w2.code = w.code and w2.id < w.id
                ) ;