2014-11-05 73 views
0

我在數據庫MySQL的選擇兩個表,並使用 「或」 變得很慢

1. USER_PHONE
用戶手機
AAA P-12345
BBB P-56454

2三個表.phone_a
ID PHONE_NUMBER
p-12345 887157481
p-16546 841461655

3.phone_b
ID PHONE_NUMBER
P-54847 48446165
P-56461 64964661

我用phone_a存儲手機號碼,並phone_b在家裏的電話號碼。
當用戶輸入一個電話號碼,我想在兩個表中搜索這個號碼。
這裏是我的查詢:

select A.user 
from 
    user_phone as A,phone_a as B,phone_b as C 
where 
    (A.phone=B.id and B.phone_number ="+9878848") or 
    (A.phone=C.id and C.phone_number ="+9878848") 

但此查詢是很慢的,我不知道爲什麼。
user_phone和phone_a有60000行,而phone_b只有600.
我覺得這個數字對於MySql很小,所以我不知道爲什麼查詢速度很慢。
我也知道使用JOIN可能會加快查詢速度,但我想知道是否有一種方法不使用JOIN,並且爲什麼這個查詢太慢?

+0

你加了'phone_number'指數? – Volatil3 2014-11-05 06:00:50

+0

http://dev.mysql.com/doc/refman/5.0/en/explain.html使用'Explain'來獲取更多關於查詢的信息。並做了正確的索引列也使用適當的數據類型? – gvgvgvijayan 2014-11-05 06:02:47

回答

1

試試這一個,沒有測試但容易調試,只是告訴我的錯誤

select A.user 
from 
user_phone as A inner join phone_a as B on a.phone=b.id inner join phone_b as C on a.phone= c.id 
where 
"+9878848" in(B.phone_number, C.phone_number)