问答详情
源自:4-5 数据库表的垂直和水平拆分

sqlercn老师,请问,一张大表水平拆分过后,如果需要查询这张大表的数据某一条,并且不知道被查询记录的id值,也就是不知道具体在哪张小表中,那么,我们应该怎么查询呢?应该join所有小表来一起查询吗?


比如:大表:


select id,name from big_table where phone=123456



小表:


select id,name

from small_table_1 as a

left join small_table_2 as b

left join small_table_3 as c

left join small_table_4 as d

where a.phone=123456 or b.phone=123456 or c.phone=123456 or d.phone=123456


或者

select id,name

from small_table_1

where phone=123456

union

select id,name

from small_table_2

where phone=123456

union

select id,name

from small_table_3

where phone=123456

union

select id,name

from small_table_4

where phone=123456


以上的两种在方式适合使用在水平拆分的表中进行查询吗?如果不适合,该怎样查询呢?怎样的查询效率相对更高呢?

提问者:sparkinzy 2014-08-27 23:46

个回答

  • sophia_yu
    2014-08-29 10:33:41
    已采纳

     这种情况,如果不知道分区键的话就只能在各个分区内扫描了。就给出的两种方法,个人认为第二种要比第一种效率高些。在水平分表设计时最好不要使用没有意义的id值做为分区键,而是选择在业务中有意义的物理主键进行拆分比较适合。 


  • huanganxin
    2015-06-24 08:18:35

    如果有100表呢?sql语句是不是很可怕 @sqlercn