简化此SQL请求

时间:2016-02-03 07:39:27

标签: php mysql sql

我有这个sql请求:

SELECT pl.*, l.loyer, l.charges, l.locataire_id, laire.nom, laire.prenom,
       l.chambre_id, c.numero, c.etage, c.maison_id, m.titre_crm 
FROM
    (
    SELECT spl.id, spl.location_id, spl.mois, spl.annee, spl.loyer_paye
    from locations sl 
        LEFT JOIN
            (
            SELECT * FROM paiement_loyer 
            union 
            SELECT 9999, usl.id, (MONTH(NOW())-1), YEAR(NOW()), 0 
            FROM locations usl 
            WHERE usl.id not in (SELECT location_id FROM paiement_loyer) || 
                                (select count(*) FROM paiement_loyer
                                 WHERE location_id = usl.id AND annee = YEAR(NOW())
              AND mois=(MONTH(NOW())-1) ) = 0
            ) spl ON sl.id = spl.location_id
    where sl.date_debut <= CURDATE() && CURDATE() <= sl.date_fin
    ) pl
JOIN locations l ON pl.location_id = l.id
JOIN locataires laire ON l.locataire_id = laire.id
JOIN chambres c ON l.chambre_id = c.id
JOIN maisons m ON c.maison_id = m.id
ORDER BY trim(upper(m.titre_crm)), c.numero, annee, mois

我想简化它,你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

尝试清理它。请注意,我认为第一个LEFT OUTER JOIN可能会被换成INNER JOIN。

我已将第二个UNIONed查询交换为2个查询,对于那些我已经更改它们以使用LEFT OUTER JOIN然后检查没有匹配

public static void function1()
{
   lock(otherlock1)
   {
     HASPClass.Read(...);

     // Some other code

     HASPClass.Write(...); 
    }
}

public static void function2()
{
   lock(otherlock1)
   {
      HASPClass.Read(...);

      // Some other code

      HASPClass.Write(...); 
    }
}