多个子查询需要更改为连接查询

时间:2016-06-23 12:03:02

标签: php mysql

大家好我需要这个问题的解决方案,这是我的查询看起来很有效。但由于子查询需要太多时间。给这个查询提供一个替代查询

SELECT *
FROM  `room_types`
WHERE id
IN (SELECT capacity
      FROM rooms
       WHERE id
     IN (
          SELECT DISTINCT room_id
           FROM  `reservations`
         WHERE DATE(
         START ) >=  '2016-01-10'
          AND DATE(
         END ) <=  '2016-01-15'
         AND STATUS =  'CheckedOut'
        AND id
         IN (
             SELECT op_no
             FROM  `bills`
              WHERE billed =  'Yes'
            )
       )
 )

2 个答案:

答案 0 :(得分:2)

截至您提供的查询,请尝试以下操作:

    SELECT
            `room_types`.*
    FROM
            `room_types`
            INNER JOIN `rooms` ON (`room_types`.`id` = `rooms`.`id`)
            INNER JOIN `reservations` ON (`rooms`.`id` = `reservations`.`room_id`)
            INNER JOIN `bills` ON (`reservations`.`id` = `bills`.`op_no`)
    WHERE
            DATE(`reservations`.`START`) BETWEEN '2016-01-10' AND '2016-01-15' 
            AND `reservations`.`STATUS` = 'CheckedOut'
            AND `bills`.`billed` = 'Yes'

此外,您可以对列进行索引,以使其更快。

答案 1 :(得分:1)

所以..首先尝试没有数据库架构!

   SELECT *
    FROM room_types rt
    JOIN rooms r ON r.capacity = rt.id
    JOIN reservations resa ON r.id = resa.room_id 
                           AND DATE(resa.start ) >=  '2016-01-10'
                           AND DATE(resa.end ) <=  '2016-01-15'
                           AND resa.status LIKE "CheckedOut"
    JOIN bills b ON resa.id = b.resa_id AND b.billed LIKE "Yes"

请注意&#34; rt&#34;,&#34; r&#34;,&#34; resa&#34;和&#34; b&#34;是表的别名