表結構相同,分表后如何查詢所有表的數據?可以使用union關鍵字
select * from table1 where type=1 union select * from table1 where type=1 union select * from table3 where type=1 union select * from tablen where type=1
上述代碼是對每個分表進行過濾后再連接。當然也可以先連接,再過濾數據:
select * from ( select * from table1 union select * from table1 union select * from table3 union select * from tablen ) t where t.type=1 order by t.id desc
需要注意的是,對於排序和分組,只能在外部進行,不能在使用union的同時使用。