實踐出真知!
使用union連接
select `id` from `表名` where 0=0 and active=1 and `fullname` like '王%' union
select `id` from `表名` where 0=0 and active=1 and `username` like '王%' union
select `id` from `表名` where 0=0 and active=1 and `mobile` like '王%' union
select `id` from `表名` where 0=0 and active=1 and `citizen_id_number` like '王%'
select `id` from `表名` where 0=0 and active=1 and `username` like '王%' union
select `id` from `表名` where 0=0 and active=1 and `mobile` like '王%' union
select `id` from `表名` where 0=0 and active=1 and `citizen_id_number` like '王%'
使用or
select `id` from `表名` where 0=0 and active=1
and `fullname` like '王%'
or `username` like '王%'
or `mobile` like '王%'
or `citizen_id_number` like '王%'
and `fullname` like '王%'
or `username` like '王%'
or `mobile` like '王%'
or `citizen_id_number` like '王%'
上面兩種查詢都能夠用上索引,且數據庫表中有500萬條數據的情況下:
如果查詢結果數據少的情況下,兩種查詢時間上差不多,0.006和0.005的區別,
但是當查詢結果數據量多時,union查詢時間16秒,or查詢時間0.05秒。
因為union需要掃描4遍表,再把結果結合在一起。
但是不知道下面這個度娘的說法是為什么?留待以后驗證。!

2019/07/08 17:17 驗證