看板 Database 關於我們 聯絡資訊
大家好,小弟有個問題想問大家,如下: 有兩個table分別叫 AA和BB AA: BB: ------------------ ------------------- id | usage id | usage ------------------ ------------------- 1 | 12 2 | 5 ------------------ ------------------- 2 | 4 3 | 3 ------------------ ------------------- 2 | 5 9 | 12 ------------------ ------------------- 9 | 80 11 | 1 ------------------ ------------------- 我想統計id in (1,2,3,9),我不要11: ------------------ id | count(usage) ------------------ 1 | 12 ------------------ 2 | 14 ------------------ 3 | 3 ------------------ 9 | 92 ------------------ 所以我下了語法 select id,count(usage) from (( select id,usage from AA ) union ( select id,usage from BB )) where id in (1,2,3,9) group by 1 order by 1 這樣是可行的 我想問問看大家對於這樣的統計有什麼其他方式可做嗎? 感謝大家! :D -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.37.221.44 ※ 文章網址: http://www.ptt.cc/bbs/Database/M.1404493035.A.D00.html ※ 編輯: smallyou1988 (114.37.221.44), 07/05/2014 00:57:50
smallyou1988:打錯,count要改sum XD 07/05 01:10
hhomerun:group by 1 order by 1 你確定是這樣子的嗎~~~~~~~~~~~~ 07/05 01:57
恩,在我用的資料庫這樣下是可以的,其他種的資料庫我就不知道了XD
hhomerun:想改的話, 就 where 那邊 可以變成 where id<10 或 id<=9 07/05 02:03
hhomerun:但這是你想要聽的答案嗎 其實已經沒甚麼好改了 07/05 02:04
bohei:id應該有index? 原po的這寫法會使用到index嗎? 07/05 08:58
bohei:先在裡面把條件指定好不知道有沒有差 07/05 08:59
恩,我有想過,我要篩選的兩個table是幾百萬筆資料
bohei:不過你應該要使用UNION ALL而不是UNION, UNION會把兩個table 07/05 10:12
bohei:重複的資料給剔除掉 07/05 10:12
smallyou1988:事實上我要篩選的條件有三種,有兩個是index,一個不是 07/05 12:13
※ 編輯: smallyou1988 (111.243.184.138), 07/05/2014 12:16:52 ※ 編輯: smallyou1988 (111.243.184.138), 07/05/2014 12:18:08