如何简化MySQL PHP查询

时间:2016-01-06 19:33:41

标签: php mysql

对我来说,简化此查询的最佳方法是什么?

$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";

1 个答案:

答案 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 = ?";

执行前解析你的查询。如果在关系列上找到了行数而不是使用索引。