2016-01-06 72 views
-4

什麼是簡化查詢的最佳方式?如何簡化MySQL PHP查詢

$sql = "SELECT " 
     ."b.barber_id, b.likes, b.shop_id, " 
     ."s.shop_name, s.shop_address, s.shop_city, s.shop_state, s.shop_zip, s.shop_phone, s.shop_website, " 
     ."bl.leave_time, bl.return_time, " 
     ."bw.work_day_start, bw.work_day_end, " 
     ."bd.days " 
     ."FROM " 
     ."barbers b, shops s, barber_lunch_break bl, barber_work_hours bw, barber_days_off bd " 
     ."WHERE " 
     ."b.user_id = ? " 
     ."AND s.shop_id = b.shop_id " 
     ."AND bl.barber_id = b.barber_id " 
     ."AND bw.barber_id = b.barber_id " 
     ."AND bd.barber_id = b.barber_id"; 
+0

如果您要從多個表中選擇數據,請使用連接。 –

+0

具有適當的索引 –

回答

-1

簡化以此爲

$sql = "SELECT b.barber_id, b.likes, b.shop_id, s.shop_name, s.shop_address, s.shop_city, s.shop_state, s.shop_zip, s.shop_phone, s.shop_website, bl.leave_time, bl.return_time, bw.work_day_start, bw.work_day_end, bd.days 
FROM 
barbers b 
INNER JOIN shops s ON s.shop_id = b.shop_id 
INNER JOIN barber_lunch_break bl ON bl.barber_id = b.barber_id 
INNER JOIN barber_work_hours bw ON bw.barber_id = b.barber_id 
INNER JOIN barber_days_off bd ON bd.barber_id = b.barber_id 
WHERE 
b.user_id = ?"; 

執行之前解釋你的查詢。如果您發現數量少於使用關係列上的索引的行數。