复杂的SQL语句

时间:2014-08-08 13:24:09

标签: mysql sql sqlite mysqli

我已经为下面的描述提出了一个复杂的SQL语句。 所以我解释了3个表

客户

  1. 的client_id
  2. 名称
  3. 电子邮件
  4. 预订[可以是0或1]
  5. 太一

    1. accom_id
    2. 的client_id
    3. checkin [timestamp]
    4. 结帐[时间戳]
    5. CONF

      1. conf_id
      2. 的client_id
      3. checkin [timestamp
      4. 结帐
      5. 所以查询是。我想为 [client.booked = 1] 中预订的客户选择所有记录以及 Accom 中的相应记录conf 或用户提供的签入和结帐时间戳之间。

        这就是我所拥有的。

        "SELECT `client_id` FROM `accomm` WHERE `checkin` >= $fro AND `checkout` <= $to"
        "SELECT `client_id` FROM `conf` WHERE `checkin` >= $fro AND `checkout` <= $to"
        

        显然,这会选择所提供的签入和结帐之间的所有client_id,但不会过滤客户中已预订值的ID = 1

3 个答案:

答案 0 :(得分:2)

我不会说这太复杂了:

   SELECT DISTINCT c.* 
     FROM client c
LEFT JOIN accom a
       ON a.client_id = c.client_id
      AND a.checkin BETWEEN $from AND $to
LEFT JOIN conf co
       ON co.client_id = c.client_id
      AND co.checkin BETWEEN $from AND $to
    WHERE c.booked = 1
      AND a.client_id IS NOT NULL OR co.client_id IS NOT NULL

这假设您只需要客户端记录而不需要重复。

答案 1 :(得分:0)

   SELECT c.* 
     FROM client c
    WHERE c.booked = 1
      AND ( 
            EXISTS (SELECT 1 
                      FROM accom a
                     WHERE a.client_id = c.client_id
                       AND a.checkin BETWEEN $from AND $to
                   )
            OR 
            EXISTS (SELECT 1
                      FROM conf co
                     WHERE co.client_id = c.client_id
                       AND co.checkin BETWEEN $from AND $to
                   )
          )

为了获得更好的性能,请创建以下索引:

  • 客户(已预订)
  • conf(client_id,checkin)
  • accom(client_id,checkin)

答案 2 :(得分:0)

SELECT Client.client_id, name, email, facility_type, facility_id, checkin, checkout
  FROM Client INNER JOIN (
       SELECT 'Accom' AS facility_type, accom_id AS facility_id, client_id, checkin, checkout
         FROM Accom
       UNION
       SELECT 'Conf' AS facility_type, conf_id AS facility_id, client_id, checkin, checkout
         FROM Conf
       ) AS sub
    ON Client.client_id = sub.client_id
 WHERE booked = 1 AND checkin >= $from AND checkout <= $to;