2016-04-25 30 views
0

我一直有這個問題的時間無法找到一個解決方案, 我需要從多個表中選擇使用聯合選擇ids,然後按日期排序結果,我做了這個查詢(它使用舊的MySQL版本一起使用)從多個表中選擇訂單和組

(SELECT MAX(id),UNIX_TIMESTAMP(date) AS date,stock_id, 'Purchase' as type FROM stock_entries WHERE type='entry' GROUP BY stock_id) 
       UNION 
       (SELECT MAX(id),UNIX_TIMESTAMP(date) AS date,stock_id, 'Sales' as type FROM stock_entries WHERE type='sales' GROUP BY stock_id) 
       UNION (select id,date, `order` AS stock_id, 'Inventory' as type FROM inventory_trans) 
       ORDER BY date ASC 

我想是的,我生成每次一個ID,以及還有一種類型,類型要麼是購買或銷售或庫存,和所有的結果應該是從兩個表中按日期(舊 - >新)排序,每當我運行上述查詢我有這個錯誤:

1140: In aggregated query without GROUP BY, expression #3 of SELECT list contains nonaggregated column 'system.inventory_trans.order'; this is incompatible with sql_mode=only_full_group_by 

如何詞組這個SQL查詢來獲取我,我根據最新的幀(日期ASC)上所需要的東西 - 舊的結果 - >更新的結果

謝謝

+1

考慮提供適當的CREATE和INSERT語句和期望的結果。 – Strawberry

+0

輸出每次應該是類似於id ==> 5,類型是Purchase,date => 12232434(unix time),next loop,id => 9,type是Sales,date => 122343434等等,id = > 10,類型爲庫存,日期=> 122343454,...基於採購或銷售的日期,或存儲在每個表中的庫存。 –

回答

0

請給這個查詢一個嘗試。

SELECT * FROM 
    (SELECT s.id,UNIX_TIMESTAMP(s.date) as date,s.stock_id, 
     M.newType AS type 
    FROM stock_entries s 
    INNER JOIN 
    (SELECT MAX(id) as maxid, stock_id,IF(type='entry','Purchase','Sales') as newType 
     FROM stock_entries 
     WHERE type='entry' OR type='sales' 
     GROUP BY stock_id,newtype) as M 
    ON M.maxid = s.id 
    )T1 
UNION ALL 
    (select id,`date`, `order` AS stock_id, 'Inventory' as type FROM inventory_trans) 
ORDER BY date ASC 

sqlfiddle