如果孩子有记录,请选择父母和子女

时间:2017-07-07 22:43:39

标签: sql postgresql

我有3个表:firearms_firearmbook,inventory_inventory和inventory_inventorytransaction。

我有2个案例:

  
      
  1. 如果inventory_inventory表没有库存操作为16的inventory_inventorytransaction,则显示inventory_inventory记录

  2.   
  3. 如果inventory_inventory表的inventory_inventorytransaction项目操作为16,则显示inventory_inventory和inventory_inventorytransaction.item_action_id

  4.   

查询bellow适用于第一个原因,但它不适用于第二个原因。 它应该像这样显示smth:

-----------------------------------
| id    |    serial   | action_id |
-----------------------------------
   1         MAGUM        
   2         EAGLE          
   2         EAGLE         16

查询:

SELECT FB.id, INV.serial_number, INV.id, INVT.item_action_id FROM firearms_firearmbook AS FB
LEFT JOIN inventory_inventory AS INV ON INV.id = FB.item_id
LEFT JOIN inventory_inventorytransaction AS INVT ON INVT.item_id = INV.id AND INVT.item_action_id = 16
WHERE FB.store_id = 1 

2 个答案:

答案 0 :(得分:1)

似乎如果给定项目有一个动作16记录,则输出中需要两条记录:一条记录​​在第三列中为空白,另一条记录在第三列中为16。

在这种情况下你可以这样做:

with base as (
        select      fb.id, 
                    inv.serial_number, 
                    inv.id, 
        from        firearms_firearmbook as fb
        inner join  inventory_inventory as inv 
                on  inv.id = fb.item_id
        where       fb.store_id = 1
    )
select      base.*,
            invt.item_action_id 
from        base
inner join  inventory_inventorytransaction as invt 
        on  invt.item_id = base.id 
        and invt.item_action_id = 16
union all
select      base.*, 
            null 
from        base
order by    1, 2, 3, 4 desc

答案 1 :(得分:0)

嗨,我认为这就是你的追求。

我为你描述的两种情况做了一个CASE声明。我不确定你想要的列是什么2)当你说“inventory_inventory”所以我把id列放了,你可以把它换成另一列。

我还删除了INVT.item_action_id = inventory_inventorytransaction join的16个部分,因为我不认为这是必要的,因为它是在CASE语句中处理的。

SELECT 
FB.id, 
INV.serial_number, 
INV.id, 
INVT.item_action_id, 
CASE 
  WHEN INVT.item_action_id = 16 THEN CAST(INV.id as VARCHAR)  + ' ' + CAST(INVT.item_action_id as VARCHAR) -- This is Case 2
  ELSE INV.record -- This is Case 1
END as answer
FROM firearms_firearmbook AS FB
LEFT JOIN inventory_inventory AS INV ON INV.id = FB.item_id
LEFT JOIN inventory_inventorytransaction AS INVT ON INVT.item_id = INV.id -- Removed JOIN on INVT.item_action_id = 16 and moved it to CASE
WHERE FB.store_id = 1;