2017-07-07 315 views
-1

我有3個表:firearms_firearmbook,inventory_inventory和inventory_inventorytransaction。如果孩子有記錄,選擇父母和子女

,我有2例:

  1. 如果inventory_inventory表中有16項行動,顯示inventory_inventory記錄

  2. 如果inventory_inventory表中有16項行動inventory_inventorytransaction沒有inventory_inventorytransaction,顯示inventory_inventory和inventory_inventorytransaction.item_action_id

查詢波紋管適用於第一個原因,但它不適用於第二個原因。 它應該顯示水木清華這樣的:

----------------------------------- 
| 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 
+0

@GordonLinoff完全missclicked MySQL的,謝謝:) – user3334406

+0

我沒有看到在所需的輸出產生第二個記錄的要求。 – trincot

+0

@trincot我需要它,因爲他們希望看到對該項目所做的每個更改,以及項目本身。如果物品沒有變化,則計數爲1,如果物品有變化,則計爲2 – user3334406

回答

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 
0

您好我覺得這是你以後有什麼。

我爲您描述的兩種情況做了CASE聲明。我不確定你想要什麼列2)當你說「inventory_inventory」,所以我把id列,你可以改變它的另一列。

我也刪除了INVT.item_action_id = 16的inventory_inventorytransaction連接的一部分,因爲我不認爲這是必要的,因爲它在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; 
相關問題